python - Python-二等分方法使整个应用程序崩溃

标签 python crash bisection

我的窗口应用程序有奇怪的问题。它的任务是使用对分法或割线法计算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

关于python - Python-二等分方法使整个应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59760716/

相关文章:

python - 为什么这段代码中 Python 和 Node.js 的 HMAC 结果不同?

python - 如何检查 HTML 中的某些复选框是否被选中?

VB6 故障转储符号未解决

algorithm - Python二分搜索逻辑错误-返回不准确的结果

python - 如何轻松地将数组的内容放入 pandas 数据框中?

python - 更新 python 中字典列表的值

过期处理程序运行后从后台返回时 iPhone 应用程序崩溃

cocoa - 如何调试仅在启用断点时在主循环之前崩溃的 Cocoa 应用程序?

c - 递归二分法程序停止工作

python - 牛顿法和二分算法的时间复杂度是多少?