的零,我尝试使用二分法指出,找到一个函数的根:查找根/功能
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