的零,我嘗試使用二分法指出,找到一個函數的根:查找根/功能
if f(a)*f(b) < 0 then a root exists,
then you repeat with f(a)*f(c)<0 where c = (a+b)/2
但林不知道如何修復代碼,以便它工作正常。 這是我的代碼,但它無法正常
from scipy import *
from numpy import *
def rootmethod(f, a, b, tol):
x = a
fa = sign(eval(f))
x = b
fb = sign(eval(f))
c = a + b
iterations = 0
if fa == 0:
return a
if fb == 0:
return b
calls = 0
fx = 1
while fx != 0:
iterations = iterations + 1
c *= 0.5
x = a + c
fc = sign(eval(f))
calls = calls + 1
if fc*fa >= 0:
x = a
fx = sign(eval(f))
if fc == 0 or abs(sign(fc)) < eps:
fx = sign(eval(f))
return x, iterations, calls
print rootmethod("(x-1)**3 - 1", 1, 3, 10*e-15)
新的編輯工作..但仍然不起作用
if fa*fb < 0:
while fx != 0:
iterations = iterations + 1
c = (a + b)/2.0
x = c
fc = sign(eval(f))
calls = calls + 1
if fc*fa >= 0:
x = c
fx = sign(eval(f))
if fc == 0 or abs(sign(fc)) < tol:
fx = sign(eval(f))
return x, iterations, calls
編輯:改變C =(A + B)* 2到c =(A + b)/ 2在該方法的描述中。
你能明確指出哪裏出了問題嗎?即解釋器錯誤消息,不正確的輸出(如果是這樣,示例輸入/輸出) – 2011-03-06 02:38:04
嗨,例如..這個輸入..(「x ** 3 - 4 * x ** 2 + 2 * x -4」,2, 5,10 * e-15)給出(2,1,1)其中2是根,但正確的答案是3.75 ..它不會到達,也不會超過1 – Kartik 2011-03-06 02:43:49
abs(sign(fc))
2011-03-06 02:58:14