bissection.py

#
# Bissection method
# Vincent Legat - 2018
# Ecole Polytechnique de Louvain
#

from numpy import *
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['toolbar'] = 'None'
plt.rcParams['figure.facecolor'] = 'silver'

# =========================================================================

def bissect(a,b,f,tol,nmax):
  n = 0; delta = (b-a)/2
  if (f(a)*f(b) > 0) :
    raise RuntimeError('Bad initial interval') 

  while (abs(delta) >= tol and n <= nmax) :
    delta = (b-a)/2; n = n + 1;
    x = a + delta;
    print(" x = %14.7e (Estimated error %13.7e at iteration %d)" % (x,abs(delta),n))
    if (f(x)*f(a) > 0) :
      a = x
    else :
      b = x
  if (n > nmax) :
    raise RuntimeError('Too much iterations') 
  return x
  
# ============================= mainProgram ===============================

f = lambda x : x * sin(x) - 1

xsol = bissect(0,2,f,1e-5,100)
print("The solution is %9.7f " % xsol)


plt.figure("Bissection method : soluce = %8.6f :-)" % xsol)
x = linspace(0,2,200)
plt.plot(x,f(x),'-b',linewidth=1)
plt.gca().axhline(y=0,color='k',linewidth=1)
plt.plot(xsol,f(xsol),'or',markersize=10)
plt.plot([0,2],[0,0],'ob',markersize=10)

plt.show()

# =========================================================================