【问题标题】:Taylor expansion in pythonpython中的泰勒展开
【发布时间】:2020-04-10 08:01:37
【问题描述】:

如何使用级数展开计算并打印出 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 循环的代码。感谢大家的帮助!!

【问题讨论】:

  • 请在问题中发布您的代码,而不是 cmets。
  • 什么是xn?你希望n+1 做什么?你的意思是n += 1?您的 while 语句检查 lnsum2 我认为这是 整个 结果,而不是单个术语。另外请修复缩进
  • 您好,希望能解决您的问题

标签: python series taylor-series


【解决方案1】:

也许这有点过头了,但这是一个很好的解决方案,使用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

【讨论】:

  • 你想在while循环中改变什么?如果您想更改 x,只需用循环将整个内容(导入语句除外)封装起来。 sympy 为您近似该系列的值,因此您不必担心迭代以使结果更准确...
  • 好吧,我不知道如何使用 sympy,所以我更喜欢使用 while 循环和 numpy 来执行此操作。欢呼
猜你喜欢
  • 2011-12-06
  • 1970-01-01
  • 2017-04-02
  • 2014-06-11
  • 2017-06-14
  • 2013-10-09
  • 2021-07-10
  • 1970-01-01
  • 2019-08-10
相关资源
最近更新 更多