0

二分アルゴリズムを使用して関数のルートの適切な近似値を見つけようとしていますが、コードを実行するとルート (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
4

1 に答える 1

0

投稿されたように、コードはc while ループの外側にあるため、ループ内の値を変更しないため、 aandの値はb決して変更されず、無限ループが発生します。

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
于 2014-09-14T19:17:50.177 に答える