英文:
taylor series approximation of a specific function
问题
我在这里只提供代码部分的翻译:
我在尝试为选定的函数(程序中的func(x))编写泰勒级数逼近,并绘制逼近值与精确值的图形。逼近的阶数/精度是用户指定的值。此外,这必须在不使用数组的情况下完成。
import math, matplotlib.pyplot as plt, numpy as np
order = float(input("输入泰勒级数逼近阶数 (n): "))
file_object = open("taylor.dat", "w")
x = -2*np.pi
n = 0
approx = 0
taylor_list = []
def func(x):
fx = np.sin(x)*np.exp(-x/2)
return fx
def deriv(n):
nth = ((-(math.sqrt(5))/2)**n)*np.sin(-n*np.arctan(2))
return nth
def taylor(x, n):
tx = ((deriv(n))/(np.math.factorial(n)))*(x**n)
return tx
while x <= 2*np.pi:
file_object.write(str(round(x, 10))
file_object.write(" ")
fx = func(x)
file_object.write(str(round(fx, 10))
file_object.write(" ")
if n <= order:
tx = taylor(x, n)
approx = approx + tx
n = n + 1
print(approx)
file_object.write(str(round(approx, 10))
file_object.write("\n")
taylor_list.append(approx)
x = x + (1/25)*np.pi
file_object.close()
请注意,这是您提供的代码的翻译版本,不包含问题或建议。
英文:
i'm struggling to write a Taylor series approximation for a chosen function (func(x) in the programme) and plot a graph of approximated values against exact. The order/accuracy of the approximation is a user-specified value. Also this must be done without using arrays.
import math, matplotlib.pyplot as plt, numpy as np
order = float(input("Enter the Taylor series aproximation order (n): "))
file_object = open("taylor.dat", "w")
x = -2*np.pi
n = 0
approx = 0
taylor_list = []
def func(x):
fx = np.sin(x)*np.exp(-x/2)
return fx
def deriv(n):
nth = ((-(math.sqrt(5))/2)**n)*np.sin(-n*np.arctan(2))
return nth
def taylor(x, n):
tx = ((deriv(n))/(np.math.factorial(n)))*(x**n)
return tx
while x <= 2*np.pi:
file_object.write(str(round(x, 10)))
file_object.write(" ")
fx = func(x)
file_object.write(str(round(fx, 10)))
file_object.write(" ")
if n <= order:
tx = taylor(x, n)
approx = approx + tx
n = n + 1
print(approx)
file_object.write(str(round(approx, 10)))
file_object.write("\n")
taylor_list.append(approx)
x = x + (1/25)*np.pi
file_object.close()
my issue is that the numbers received by the taylor approximation (approx) arent working no matter what degree of accuracy selected, also it converges around an arbitrary number (25.1281585765..)
the only thing left out is the graphing code which works fine. if you see any problems or suggestions, you'd make my day
答案1
得分: 0
你从不为新的 x
值重置你的 approx
和 n
,因此你只是在每个 x
值处附加第一个计算出的值。
英文:
You never reset your approx
and n
for new values of x
, so you just append the first calculated value at every value of x
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论