【发布时间】:2014-08-22 13:24:33
【问题描述】:
我正在尝试在 Python 2.7 中实现二分法函数。我真的很困惑为什么我的代码没有返回我在测试中括起来的根。
当我在代码中添加打印语句时,很明显算法正在寻找根,但我一定错过了实际语法中的一些基本内容(我是 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)
【问题讨论】:
标签: python python-2.7 return