12:45 PM

Python program to find solution of a polynomial using Newtons method



The Newtons method is used to find the root of an n digree polynomial by successive guesses.The simple algorithm to find the root using Newtons method is.
  1. Take initial guess as x_0
  2. Now evaluate the value of the polynomial at x_0
  3. Check if the value is near to zero within a small epsilon (say .01). If yes we call x_0 as the root 
  4. calculate new value of x_0 as x_0=x_0-[f(x)/f'(x)] 
  5. Check if this new value is close to root and so on until you find a root


Here is a simple python program to find the root of a polynomial.The polynomial is represented as a list with the index of each number as the power of x.Three procedures are used to find the value of the polynomial,its derivative and to compute the root of the polynomial

The program returns a list with root and number of itterations performed to find the root

=================================================== 



def evaluate(poly, x):
    value=0.0
    for index in range(len(poly)):
        value  = value+(x**index)*poly[index]
    return value

def Deriv(poly):
    for index in range(len(poly)):
            poly[index]*=index
    poly.pop(0)
    if len(poly) == 0:
        poly.insert(0,0.0)
    return poly

def Root(poly, x_0, epsilon):
    value = (evaluate(poly,x_0))
    poly1=[]
    for num  in poly:
            poly1.append(num)   
    Deriv(poly1)
    count = 0
    while abs(value)  >= epsilon:
        derivalue=(evaluate(poly1,x_0))
        if derivalue == 0:
            x_0 = 0
            break
        x_0 = x_0 - (value/derivalue)
        value=(evaluate(poly,x_0))
        count += 1
    return [x_0,count]
   
  def main():
    poly = [-13.39, 0.0, 17.5, 3.0, 1.0]   
    #poly=[1]
    x_0 = 0.1
    epsilon = .0001
    print computeRoot(poly, x_0, epsilon)   
           
if __name__ == '__main__':
    main()


===================================================
===fa 
  

0 comments: