簡體   English   中英

python中的泰勒展開

[英]Taylor expansion in python

如何使用級數展開計算和打印 ln(1+x) 的值:

ln(1+x) 展開

在此處輸入圖片說明

使用 while 循環並包括大小大於 10-8 的項。 打印出每個項數的總和以顯示結果收斂。

到目前為止,這是我的代碼,但它計算出 lnsum2 是一個非常大的數字,因此永遠不會結束。

n=1 
lnsum2= np.cumsum((((-1)**(n+1)*(x**n)/n))) 
while lnsum2>10**-8: 
       n+=1 
       lnsum2 = lnsum2 + np.cumsum((((-1)**(n+1)*(x**n)/n))) 
else: print('The sum of terms greater than 10^-8 is:', lnsum2)

非常感謝。

是的,我現在有使用 while 循環的代碼。 謝謝大家的幫助!!

也許這有點過頭了,但這里有一個很好的解決方案,使用sympy來評估無限級數。

from sympy.abc import k
from sympy import Sum, oo as inf
import math

x = 0.5

result = Sum(
    (
        x**(2*k-1) /
         (2*k-1)
    ) - (
        x**(2*k) / (2*k)
    ),

    (k, 1, inf)).doit()

#print(result) # 0.5*hyper((0.5, 1), (3/2,), 0.25) - 0.14384103622589
print(float(result)) # 0.4054651081081644

print(math.log(x+1, math.e)) # 0.4054651081081644

編輯:

我認為您的原始代碼的問題在於您還沒有完全實現該系列(如果我正確理解了您問題中的數字)。 看起來您嘗試實現的系列可以表示為

      x^(2n-1)       x^(2n)
( +  ----------  -  -------- ... for n = 1 to n = infinity )
        2n-1           2n

而你的代碼實際上實現了這個系列

 (-1)^2 * (x * 1)    (  (-1)^(n+1) * (x^n)                                  )
----------------- + (  --------------------  ... for n = 2 to n = infinity   ) 
        1            (          n                                           )

編輯2:

如果您真的必須自己進行迭代,而不是使用 sympy,這里是有效的代碼:

import math

x = 0.5

n=0
sums = []

while True:
    n += 1
    this_sum = (x**(2*n-1) / (2*n-1)) - (x**(2*n) / (2*n))
    if abs(this_sum) < 1e-8:
        break

    sums.append(this_sum)

lnsum = sum(sums)

print('The sum of terms greater than 10^-8 is:\t\t', lnsum)
print('math.log yields:\t\t\t\t', math.log(x+1, math.e))

輸出:

The sum of terms greater than 10^-8 is:      0.4054651046035002
math.log yields:                             0.4054651081081644

暫無
暫無

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

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