Skip to content

Instantly share code, notes, and snippets.

@psbots psbots/bisection.py
Last active Dec 13, 2015

Embed
What would you like to do?
Bisection method to find roots of a non-linear equation
#Bisection Method to find roots of a non linear equation
#Praveen Sridhar
#psbots.blogspot.com
def bisection(function,lower_bound,upper_bound,error_tolerance=1.0e-4):
fu=function(upper_bound)
if fu==0.0 : return upper_bound
fl=function(lower_bound)
if fl==0.0 : return lower_bound
if fu*fl > 0.0: #if the product of the function values at the two bounds is positive, then they do not bracket a root
return None
else:
mid=(lower_bound+upper_bound)/2
error=(upper_bound-lower_bound)/2
while(error>error_tolerance): #the loop executes till the desired level of accuracy is attainedfm=function(mid)
fu=function(upper_bound)
fl=function(lower_bound)
#if the middle value is indeed the root, it is returned as the root
if fm==0.0 : return mid
#if the actual root lies between upper bound and the middle value, the lower bound is set to be the middle value
elif fu*fm < 0.0 : lower_bound=mid
##if the actual root lies between lower bound and the middle value, the upper bound is set to be the middle value
elif fl*fm < 0.0 : upper_bound=mid
mid=(lower_bound+upper_bound)/2
error=(upper_bound-lower_bound)/2
return mid
def func(x): #defining the non-linear equation to be solved as a function
return x**3-3*x+1
x=bisection(func,1.0,2.0) #running the bisection function for the function 'func'
print x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.