【題目描述】編寫程序,使用牛頓迭代法求方程 在x附近的一個實根。
【練習要求】請給出源代碼程序和運行測試結果,源代碼程序要求添加必要的注釋。
【輸入格式】請在一行中輸入方程系數a、b、c、d和實數x,數據中間以空格為間隔。
【輸出格式】對每一組輸入的數據,輸出牛頓迭代法求出的實根(格式為保留小數點后2位,四舍五入)。
【輸入樣例】1.0 2.0 3.0 4.0 1.0
【輸出樣例】-1.65
關於牛頓迭代法是什么,參考:如何通俗易懂地講解牛頓迭代法求開方(數值分析)?
代碼:
num = input() n1 = num.split(" ") n = [] for i in n1[::]: if i == '': n1.remove(i) for i in n1: n.append(float(i)) def f(x): return n[0] * pow(x, 3) + n[1] * pow(x, 2) + n[2] * pow(x, 1) + n[3] def fd(x): return 3 * n[0] * pow(x, 2) + 2 * n[1] * pow(x, 1) + n[2] def newtonMethod(assum): x = assum a = f(x) b = fd(x) if f(x) == 0.0: print(round(x, 2)) return x else: next = x - a / b # print('next x = ' + str(next)) # 輸出下一條切線的值 if a - f(next) < 1e-6: print(round(next, 2)) # 設置跳出條件,同時輸出滿足f(x) = 0 的x的值 else: return newtonMethod(next) # 遞歸 newtonMethod(n[4])