[英]iterative Newton's method
I have got this code to solve Newton's method for a given polynomial and initial guess value.我有这个代码来解决给定多项式和初始猜测值的牛顿方法。 I want to turn into an iterative process which Newton's method actually is.
我想变成牛顿方法实际上是的迭代过程。 The program should keeping running till the output value "x_n" becomes constant.
程序应该一直运行,直到 output 值“x_n”变为常数。 And that final value of x_n is the actual root.
x_n 的最终值是实际的根。 Also, while using this method in my algorithm it should always produce a positive root between 0 and 1. So does converting the negative output (root) into a positive number would make any difference?
此外,在我的算法中使用这种方法时,它应该始终产生一个介于 0 和 1 之间的正根。那么将负 output(根)转换为正数会产生什么不同吗? Thank you.
谢谢你。
import copy
poly = [[-0.25,3], [0.375,2], [-0.375,1], [-3.1,0]]
def poly_diff(poly):
""" Differentiate a polynomial. """
newlist = copy.deepcopy(poly)
for term in newlist:
term[0] *= term[1]
term[1] -= 1
return newlist
def poly_apply(poly, x):
""" Apply a value to a polynomial. """
sum = 0.0
for term in poly:
sum += term[0] * (x ** term[1])
return sum
def poly_root(poly):
""" Returns a root of the polynomial"""
poly_d = poly_diff(poly)
x = float(raw_input("Enter initial guess:"))
x_n = x - (float(poly_apply(poly, x)) / poly_apply(poly_d, x))
print x_n
if __name__ == "__main__" :
poly_root(poly)
First, in poly_diff, you should check to see if the exponent is zero, and if so simply remove that term from the result.首先,在 poly_diff 中,您应该检查指数是否为零,如果是,只需从结果中删除该项。 Otherwise you will end up with the derivative being undefined at zero.
否则,您最终会得到未定义为零的导数。
def poly_root(poly):
""" Returns a root of the polynomial"""
poly_d = poly_diff(poly)
x = None
x_n = float(raw_input("Enter initial guess:"))
while x != x_n:
x = x_n
x_n = x - (float(poly_apply(poly, x)) / poly_apply(poly_d, x))
return x_n
That should do it.那应该这样做。 However, I think it is possible that for certain polynomials this may not terminate, due to floating point rounding error.
但是,我认为对于某些多项式,由于浮点舍入误差,这可能不会终止。 It may end up in a repeating cycle of approximations that differ only in the least significant bits.
它可能会以重复的近似循环结束,这些近似仅在最低有效位上有所不同。 You might terminate when the percentage of change reaches a lower limit, or after a number of iterations.
您可能会在更改百分比达到下限或经过多次迭代后终止。
import copy
poly = [[1,64], [2,109], [3,137], [4,138], [5,171], [6,170]]
def poly_diff(poly):
newlist = copy.deepcopy(poly)
for term in newlist:
term[0] *= term[1]
term[1] -= 1
return newlist
def poly_apply(poly, x):
sum = 0.0
for term in poly:
sum += term[0] * (x ** term[1])
return sum
def poly_root(poly):
poly_d = poly_diff(poly)
x = float(input("Enter initial guess:"))
x_n = x - (float(poly_apply(poly, x)) / poly_apply(poly_d, x))
print (x_n)
if __name__ == "__main__" :
poly_root(poly)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.