我的窗口应用程序有奇怪的问题。它的任务是使用对分法或割线法计算n次多项式的根,这取决于用户的意愿。现在,我的问题开始了,因为如果我将一定的时间间隔放入方法中,则有时在单击星号按钮后有时会崩溃,但是如果它是第一次,那么如果我将时间间隔[a,b]调整为“a ”的先行结果,它崩溃无误。我什至没有提到我的割线方法变得疯狂,对于某些时间间隔而言,答案是好的,对于某些答案而言,它们只是随机的。
def secant(self,f, a, b, err):
fb=f(b)
while np.absolute(fb)>err:
midPoint=b-(b-a)*fb/(fb-f(a))
a=b
b=midPoint
fb=f(b)
return b
#--------------------------------------------------------------
def bisection(self,f,a,b,err):
while np.absolute(b-a)>err:
midPoint=(a+b)*0.5
if f(midPoint)*f(a)<0:
b=midPoint
midPoint=(a+b)*0.5
if f(midPoint)*f(b)<0:
a=midPoint
midPoint=(a+b)*0.5
return midPoint
请您参考如下方法:
def bisect(f, a, b, e):
""" Bisection Method
inputs:
f - a function.
a - Starting interval
b - Ending interval
e - Acceptable value for 0; (e.g. consider 0.001 == 0)
"""
iterations = 0
while True:
c = (a + b)/2
if b - c <= e:
print('Iterated:', iterations, 'times.')
return c
elif f(b)*f(c) <= 0:
a = c
else:
b = c
iterations += 1
查看更多 here。