2017-01-16 69 views
1

epsilon設置爲0.1,但它給我的結果,直到1.2。我不知道是什麼原因造成的。誰能幫忙?python epsilon錯誤的計算

def evaluate_poly(poly, x): 
    total = 0.0 
    for i in range(len(poly)): 
     total += poly[i] * (x ** i) 

    return total 

def compute_deriv(poly): 
    deriv = [] 
    if len(poly) < 2: 
     return [0.0] 
    else: 
     for i in range(1, len(poly)): 
      deriv.append(float(poly[i] * i)) 
     return deriv 

def compute_root(poly, x_0, epsilon): 
    num = 0 
    root = x_0 
    while abs(evaluate_poly(poly, root)) >= epsilon: 
     root = root - evaluate_poly(poly, root)/evaluate_poly(compute_deriv(poly), root) 
     num += 1 
    return [root, num] 

print(compute_root((1.0,-2.0,1.0), 14, 0.1)) 
+0

請首先確定您的問題:什麼是epsilon,你想要計算什麼,... –

+0

「epsilon設置爲1.1」 - 你的代碼似乎使用0.1。 「但它給我的結果,直到1.2。」 - 那有什麼意思?如果你想說服任何人,你所看到的不僅僅是浮點四捨五入錯誤,你需要提供更多細節。 –

+0

@SergeBallesta我明白(雖然看起來更像牛頓的方法),但他們的代碼使用epsilon = 0.1,而在問題中他們說他們已經將epsilon設置爲1.1。 –

回答

2

小量爲Y錯誤(如果你願意評價多),但是你的1.2結果......是x值,其中y是0。在這種情況下,你y是0.0412和低於0.1這樣的代碼沒問題。

在compute_root改變你的回報:

return [root, num, abs(evaluate_poly(poly, root))] 
3

你正在試圖解決數字X - 2 * X + 1 = 0。我們知道這個方程在x = 1雙根。但是在那個點(x = 1),導數(2 * x - 2)是0.這意味着y中的誤差總是比x中的誤差低一個數量級,所以x = 1.2,y 〜0.04 < 0.1毫無意外。

該差值X ñ - X N-1將是錯誤的X一個更好的猜測:

def compute_root1(poly, x_0, epsilon): 
    num = 0 
    root = x_0 
    while True: 
     root1 = root - evaluate_poly(poly, root)/evaluate_poly(compute_deriv(poly), root) 
     if abs(root1 - root) < epsilon: break 
     num += 1 
     root = root1 
    return [root1, num+1] 

它提供:

>>> print(compute_root1((1.0,-2.0,1.0), 14, 0.1)) 
[1.05078125, 8]