所以我最終試圖使用霍納規則(http://mathworld.wolfram.com/HornersRule.html)來評估多項式,並創建一個函數來評估多項式。無論如何,我的問題在於我如何編寫函數;它適用於簡單多項式,如3x^2 + 2x^1 + 5等等。但是一旦你開始評估一個具有浮點數的多項式(像1.8953343e-20這樣瘋狂的東西),它就會失去精度。 因爲我正在使用這個函數來使用牛頓法(http://tutorial.math.lamar.edu/Classes/CalcI/NewtonsMethod.aspx)評估多項式的根,所以我需要這是精確的,所以它不會因爲小的舍入誤差而丟失它的值。Python中的精確錯誤
我已經與另外兩個人解決了問題在於evaluatePoly()函數,而不是我評估牛頓方法的其他函數。此外,我最初通常評估多項式(將x乘以度數,乘以常數等),然後提取正確的答案。但是,這項任務需要使用Horner的規則來進行更簡單的計算。
這是我下面的代碼:
def evaluatePoly(poly, x_):
"""Evaluates the polynomial at x = x_ and returns the result as a floating
point number using Horner's rule"""
#http://mathworld.wolfram.com/HornersRule.html
total = 0.
polyRev = poly[::-1]
for nn in polyRev:
total = total * x_
total = total + nn
return total
注:我已經嘗試使用浮動設置NN,X_,(總* X_)爲花車()。
這是我收到的輸出:
Polynomial: 5040x^0 + 1602x^1 + 1127x^2 - 214x^3 - 75x^4 + 4x^5 + 1x^6
Derivative: 1602x^0 + 2254x^1 - 642x^2 - 300x^3 + 20x^4 + 6x^5
(6.9027369297630505, False)
Starting at 100.00, no root found, last estimate was 6.90, giving value f(6.90) = -6.366463e-12
(6.9027369297630505, False)
Starting at 10.00, no root found, last estimate was 6.90, giving value f(6.90) = -6.366463e-12
(-2.6575456505038764, False)
Starting at 0.00, no root found, last estimate was -2.66, giving value f(-2.66) = 8.839758e+03
(-8.106973924480215, False)
Starting at -10.00, no root found, last estimate was -8.11, giving value f(-8.11) = -1.364242e-11
(-8.106973924480215, False)
Starting at -100.00, no root found, last estimate was -8.11, giving value f(-8.11) = -1.364242e-11
這是輸出我需要:
Polynomial: 5040x^0 + 1602x^1 + 1127x^2 - 214x^3 - 75x^4 + 4x^5 + 1x^6
Derivative: 1602x^0 + 2254x^1 - 642x^2 - 300x^3 + 20x^4 + 6x^5
(6.9027369297630505, False)
Starting at 100.00, no root found, last estimate was 6.90,giving value f(6.90) = -2.91038e-11
(6.9027369297630505, False)
Starting at 10.00, no root found, last estimate was 6.90,giving value f(6.90) = -2.91038e-11
(-2.657545650503874, False)
Starting at 0.00, no root found, last estimate was -2.66,giving value f(-2.66) = 8.83976e+03
(-8.106973924480215, True)
Starting at -10.00, root found at x = -8.11, giving value f(-8.11)= 0.000000e+00
(-8.106973924480215, True)
Starting at -100.00, root found at x = -8.11, giving value f(-8.11)= 0.000000e+00
注:請忽略出錯輸出的元組;這是我的牛頓方法的結果,第一個結果是根,第二個結果是指出它是否是根。
如果你的數字相對較遠,那麼你只是運行到雙精度限制。 – Evert
雖然您的問題並不在您所展示的代碼中。這只是一個簡單的評估,但沒有根搜索(例如,與0比較)。您應該在可用精度*內比較零*。 – Evert