我在python中的二分法代码不会返回root

时间:2014-09-14 18:41:50

标签: python numpy bisection

我试图使用二分算法找到函数根的良好近似值,但是,当我运行代码时它不会返回根(c)。这是我的代码。

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-10,10,201)

def f(x): 
    return np.cos(x) 

plt.figure()
plt.plot(x,f(x),label = 'cosx')
plt.xlabel('independent variable x')
plt.ylabel('dependent variable y')
plt.title('')

plt.show()

TOL = 10**-6
a = 0
b = 1

def bisection(a,b,TOL):
    c = (a+b)/2.0  
    while (b-a)/2.0 > TOL:
        if f(c)==0:
            return c
        elif f(a)*f(c)<0:
            b = c
        else:
            a = c
    c = (a+b)/2.0
    return c

1 个答案:

答案 0 :(得分:0)

发布后,您的代码不会更改循环中c的值,因为它位于while循环之外,因此ab的值永远不会更改,从而导致无限循环:

def bisection(a,b,TOL):
    c = (a+b)/2.0  
    while (b-a)/2.0 > TOL:
        if f(c)==0:
            return c
        elif f(a)*f(c)<0:
            b = c
        else:
            a = c
        c = (a+b)/2.0 # put inside the while
    return c

要通过循环查看c的值,请添加一个print语句:

def bisection(a, b, TOL):
    c = (a + b) / 2.0
    while (b - a) / 2.0 > TOL:
        if f(c) == 0:
            return c
        elif f(a) * f(c) < 0:
            b = c
        else:
            a = c
        c = (a + b) / 2.0
        print ("Current value of c is {}".format(c)) 
    return c