Python中的泰勒展开

时间:2019-12-17 19:10:14

标签: python series taylor-series

如何使用级数展开来计算和打印ln(1 + x)的值:

ln(1 + x)展开

enter image description here

使用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循环的代码。感谢您的所有帮助!

1 个答案:

答案 0 :(得分:2)

也许这有点过分,但这是使用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
相关问题