1
我想在Python 2.7中实现一个二分法函数。我非常难以理解为什么我的代码没有返回包含在我的测试中的根。函数不返回值(Python 2.7)
当我在代码中打印语句时,很明显算法找到了根,但是我一定在实际语法中遗漏了一些基本的东西(我是python的一个完整的newby)。
代码是在这里:
def bisection(a,b,fun,tol):
c = (a+b)/2.0
if (b-a)/2.0 <= tol:
#Debugging print statement 1:
#print 'SOL1: c = ', c
return c
if fun(c) == 0:
#Debugging print statement 2:
#print 'SOL2: c = ', c
return c
elif fun(a)*fun(c) < 0:
b = c
else:
a = c
print 'a =', a
print 'b =', b
bisection(a, b, fun, tol)
def tstr(x):
return 2*(x**2) - 3*x + 1
sol = bisection(0, 0.9, tstr, 0.01)
唉唉,精彩纷呈。谢啦。 – Aidenhjj