使用牛頓迭代法求方程 在x附近的一個實根。python
賦值X,即迭代初值;用初值x代入方程中計算此時的f(x)=(a * x * x * x + b * x * x + c * x + d)和f’(x)=(3 * a * x * x + 2 * b * x + c)blog
計算增量f(x)/f’(x);計算下一個x: x-f(x)/f’(x); 把新產生的x替換 x: x=x-f(x)/f’(x),循環; input
若d絕對值大於0.00001,則重複上述步驟。
it
def diedai(a, b, c, d,X): x = X if a == 0 and c ** 2 - 4 * b * d < 0: print("無解") elif a == 0 and b == 0 and c == 0 and d != 0: print("無解") elif a == 0 and b == 0 and c == 0 and d == 0: print("恆等") else: while abs(a * x * x * x + b * x * x + c * x + d) > 0.000001: x = x - (a * x * x * x + b * x * x + c * x + d) / (3 * a * x * x + 2 * b * x + c) print("x=%.2f" % x) a,b,c,d,x=input().split() diedai(int(a),int(b),int(c),int(d),int(x))