我正在尝试在Python 2.7中实现二分法方法。我真的很难过为什么我的代码没有返回我在测试中包围的根。
当我在代码中放置print语句时,很明显算法找到了根,但我必须错过实际语法中的基本内容(我是python的完全新手)。
代码在这里:
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)
答案 0 :(得分:4)
你最后忽略了递归调用;你需要显式返回它的返回值:
return bisection(a, b, fun, tol)
这里不使用return
意味着忽略了递归调用返回值,并且外部调用函数在没有明确return
stamenent的情况下结束,因此返回{{1} }。
通过此更改,None
实际设置为:
sol