0

I am trying to find a good approximation to the root of a function using a bisection algorithm, however, when I run the code it doesnt return the root (c). Here is my code.

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
kecer
  • 3,031
  • 2
  • 21
  • 24
Truxton Boyce
  • 183
  • 2
  • 2
  • 7
  • Also, it is incredibly difficult to figure out how to format multiple lines of code on this site...any help with that would be good too. I mean, I wanted to just copy my entire code with one click, but it wouldnt let me do that...very annoying. – Truxton Boyce Sep 14 '14 at 18:42
  • 1
    Copy and paste the code. Then select the code, and with the code selected hit the curly-brace button `{}` or type control-K. – DSM Sep 14 '14 at 18:44
  • the values of b and a never change so you will loop forever – Padraic Cunningham Sep 14 '14 at 19:16

1 Answers1

0

As posted your code don't change the values of c in the loop as it is outside the while loop so the value of a and b never change causing an infinite loop:

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

To see the value of c through the loop add a print statement:

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
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321