计算ln(1 + x)的级数展开

时间:2019-12-09 10:15:55

标签: python numpy

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

ln(1+x) expansion

使用while循环并包含大小大于10 -8 的项。 打印出每个项数的总和以显示收敛的结果。

非常感谢。

1 个答案:

答案 0 :(得分:1)

因此,我查看了您的问题,您并没有真正清楚地表达该公式。

如果我是对的,那么您正在寻找ln(1 + x)的泰勒展开式,该展开式仅适用于介于1和-1之间的x值,如以下公式所示:

ln(1+x) Taylor expansion

因此,为了做到这一点,我将迭代的元素定义为一个函数,然后将其集成到for循环中。

请记住,我们首先必须使用一个验证循环来获取x值,该验证循环验证x在1到-1之间,以及我们要在本系列中进行的迭代次数。

此后,我们定义3个变量:

  • 我们初始化一个等于0的float变量,我们将向其添加序列元素,这将使我们获得ln(1 + x)的最终值答案
  • 一个迭代列表,使我们可以观察从函数的每次迭代获得的每个单独的值

  • 最终列表,向我们显示该值的进展,直到迭代结束。

在执行了上面的代码中的for循环后,我们将完成所有列表,然后您可以自由地将这些值绘制在最终列表上的图形上。

在您将在下面看到的代码中,我对图表(matplotlib)的了解不深,但是我只是想了解问题的实质,并绘制一个图。

我真的希望这会有所帮助!

代码:

import numpy as np
import matplotlib.pyplot as plt 

def series_formula(x_value,n):
    iteration = ((-1)**(n+1))*((x_value**n)/n)
    return iteration


#We intialise x_value in order to enter a while loop which will verify the values of x we can use for our expansion
x_value = -2

while x_value <= -1 or x_value > 1:
    x_value = float(input('User, please enter your desired x value for the series expansion between -1 and 1:'))
    if x_value <= -1 and x_value > 1:
        print("Error, this expansion can't take values which are larger than 1 or smaller than or equal to -1, try again.\n")

n = int(input('User, please enter the number of iterations you wish to have in the series: '))


#Initialize a sum counter for the series which we shall use within the while loop 
iteration_list = [] 
sum_list = []
sum = 0

for i in range(1,n+1):
    iteration_list.append(series_formula(x_value,i))
    sum += series_formula(x_value,i);
    sum_list.append(sum)




print("Verification of series for ln(1+x) approximation: ",np.log(1+x_value))
print("Approximation:",sum)
print("Iteration values:", iteration_list)
print("Progression evolution", sum_list)

#If we want to show the progression of the line in a matplotlib graph
plt.plot(range(1,n+1),sum_list)
plt.plot(np.log(x_value+1))