我正在尝试使用牛顿方法来查找示例函数的根,但它不起作用。救命? (Python)打印的值最初似乎是正确的,然后失控。
类Newton_Method():
#Use Newton's Method in order to find the nth approximation of the root of f(x).
#Given:
# f(x) = 48x(1+x)^60 - (1+x)^60 + 1
# f'(x) = 12(1+x)^59(244x-1)
# x1 = 0.0076
# x2 = x1 - (f(x1)/f'(x1))
x1 = 0.0076
x2 = None
f = 48*x1*(1+x1)**60 - (1+x1)**60 + 1
df = 12*(1+x1)**59*(244*x1-1)
n = int(raw_input('Enter the number of times to approximate the root: '))
for i in range(n):
x2 = x1 - (f/df)
print x2 #I print to check, but the values are all jacked up. :/
x1 = x2
print x1
答案 0 :(得分:0)
我不知道你的方程式,但python语法是这样的:
def f(x):
return 48 * x * (1 + x) ** 60 - (1 + x) ** 60 + 1
def df(x):
return 12 * (1 + x) ** 59 * (244 * x - 1)
n = int(raw_input('Enter the number of times to approximate the root: '))
x = 0.0076
for i in range(n):
x = x - f(x) / df(x)
print x