Search This Blog

Saturday, March 12, 2011

Bisection method


# Bisection method

def f(x):
return (x**2-2)
e=0.00001
a=float(input('Enter limit a   '))
b=float(input('Enter limit b   '))
if f(a)*f(b)<=0.0:
while abs(a-b)>=e:

x=(a+b)/2  
if(f(x)*f(a)>0):
a=x
else:
b=x
print'The best approximation is %.5f'%x
else:
print' sorry !!! There is no root  between',a,'and ',b


Fixed Iteration method


# Fixed iteration method to find approximate root
from math import sqrt
#function definition
def f(x):
    f1=1.0/sqrt(1+x)
    return f1

e=0.0001
x0=float(input("Enter starting value   "))

while abs(f(x0)-x0)>=e:
    x0=f(x0)
  
  
print 'The best approximation to root is %.4f'%(x0)

Newton-Raphson method


#Newton-Raphson method to find approximate root

from math import *
e=0.00001
#function definition
def f(x):
    return x*sin(x)+cos(x)

#differential of the function
def fp(x):
    return x*cos(x)


x0=float(input("Enter the approximate root \t"))

while 1:
    x1=x0-f(x0)/fp(x0)

    if abs(x0-x1)<e:
        break
    else:
        x0=x1

print "The best approximation to root is   %.5f"%x1