簡體   English   中英

如何在不使用內循環或 if-else 的情況下計算 sin(x) 的泰勒級數的總和?

[英]How to calculate sum of terms of Taylor series of sin(x) without using inner loops or if-else?

  1. 我不能使用內循環
  2. 我不能使用 if-else

我需要計算以下系列:

x - x^3/3! + x^5/5! - x^7/7! + x^9/9! ...

我在想類似以下的事情:

n =1
x =0.3
one=1
fact1=1
fact2=1
term =0
sum =0
for i in range(1, n+1, 2):
    one = one * (-1)
    fact1 = fact1*i
    fact2 = fact2*i+1
    fact = fact1*fact2
    x = x * x
    term = x/fact
    sum = sum + term

但是,我發現很難同時保持事實和 x 的乘法。

您想計算項的總和。 每一項都是前一項乘以-1 * x * x並除以n * (n+1) 就這么寫:

def func(x):
    eps = 1e-6                   # the expected precision order
    term = x
    sum = term
    n = 1
    while True:
        term *= -x * x
        term /= (n+1) * (n+2)
        if abs(term) < eps: break
        sum += term
        n += 2
    return sum

演示:

>>> func(math.pi / 6)
0.4999999918690232

按預期給出 0.5,精度為 10e-6


注意:該系列是sin函數的眾所周知的發展......

這不是 sin(x) 的泰勒級數嗎? 你能使用列表理解嗎? 列表理解可能類似於

x = 0.3
sum([ (-1)**(n+1) * x**(2n-1) / fact(2n-1) for n in range(1, numOfTerms)])

如果你不能使用列表理解,你可以像這樣簡單地循環

x=0.3
terms = []
for n in range(1, numberOfTerms):
  term = (-1)**(n+1)*x**(2n-1)/fact(2n-1)
  terms.append(term)

sumOfTerms = sum(terms)

然后通過遞歸計算階乘:

def fact(k):
  if (k == 1):
    return n
  else:
    return fact(k-1)*k

使用 Striling 的近似計算階乘:

fact(k) = sqrt(2*pi*k)*k**k*e**(-k)

這里沒有 if-else 也沒有內部循環。 但是隨后會出現精度誤差,需要使用數學庫來獲取常量或獲得更多精度誤差,並對 pi 和 e 使用硬編碼值。

希望這可以幫助!

n = NUMBER_OF_TERMS
x = VALUE_OF_X
m = -1
sum = x # Final sum

def fact(i):
    f = 1
    while i >= 1:
        f = f * i
        i = i - 1
    return f

for i in range(1, n):
    r = 2 * i + 1
    a = pow (x , r)
    term = a * m / fact(r);
    sum = sum + term;
    m = m * (-1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM