这种二分法不会返回结果

时间:2016-02-13 21:04:34

标签: python return-value

我正在尝试使用bisection方法找到图表的根,但我无法让Spyder返回值。
我是一个完全新手,所以我可能犯了一个容易犯的错误,但我找不到它。

以下是我的主题:

x1 = -7
x3 = 4
x2 = 0.5 * (x1 + x3)

min = 0.0001

a = 1 
b = 2 
c = -4

def f(x):
    return a*x*x + b*x + c

def bisection(x1,x3,min):
    while x2 > min:
        x2 = 0.5 * (x1 + x3) 
        if f(x2) == 0:
            return x2 
        elif f(x1)*f(x2) < 0:
            x3 = x2
        else:
            x1 = x2
        x2 = 0.5 * (x1 + x3)

    return x2

print bisection(x1,x3,min)

任何帮助都将不胜感激!

2 个答案:

答案 0 :(得分:1)

我最终复制了the psuedocode from Wikipedia

a = 1
b = 2
c = -4

def f(x):
    return a*(x**2) + b*x + c

def sign(v):
    return -1 if v < 0 else 0 if v == 0 else 1

def bisection(f, a, b, eps=1e-4, maxIters=10000):
    count = 1
    while count < maxIters:
        c = 0.5 * (a + b)

        if f(c) == 0 or 0.5*(b - a) <= eps:
            break

        count += 1
        fc = f(c)
        fa = f(a)
        if sign(fc) == sign(fa):
            a = c
        else:
            b = c

    return c

print bisection(f, -7, 4, eps=1e-10) # -3.23606797746
print bisection(f, 1, 4, eps=1e-10) # 1.23606797741

答案 1 :(得分:0)

x2x1x3的平均值,可能永远不会低于min。您必须检查函数值f(x2)

def bisection(f, x1, x3, eps=1e-4):
    while True:
        x2 = 0.5 * (x1 + x3)
        w = f(x2)
        if abs(w) < eps:
            break
        if w < 0:
            x1 = x2
        else:
            x3 = x2
    return x2

def f(x):
    return a*x*x + b*x + c

print bisection(f, -7 , 4)