Write a program to solve system of nonlinear equations using Newtons method.

QUESTION 

Write a program to solve system of nonlinear equations using Newtons method.

16 = 16x4 + 16y4 +z4

3 = x2 + y2 + z2

0 = x3 – y

Run Newtons method for 5 iterations and save the result of each iteration in guesses. As a starting guess, take each variable to be 1.

In the starter code ,you are provided with the function f that represents the system of nonlinear equations as well as the array w that should serve as your initial guess.

 

SUMMARY

For the three given equations, the Newton method is applied to find the roots of x, y, and z up to 5 iterations, and this output is stored in a 2D guesses numpy array. 

 

EXPLANATION

A function f is used to return the three equations, whose roots are to be found, as a numpy array. The function Derfx() is used to find the derivative of the first equation. A function called Derfy() is used to find the derivative of the 2nd equation. Function Derfz() is implemented to have the derivative of the 3rd equation. To this, the newton method is implemented for only 5 iterations and in each iteration, the updated 3 equation values are appended to the guesses numpy array. In each iteration, the value f()/Df() is subtracted from the original equation value. 

 

CODE

import numpy as np 

import numpy.linalg as la

def f(w):

  x,y,z=w

  return np.array([

                   16*x**4 + 16*y**4 + z**4 -16,

                   x**2 + y**2 + z**2 -3,

                   x**3 - y

  ])

def Derfx(x,y,z):

  return 64*x**3 + 64*y**3 + 4*z**3

def Derfy(x,y,z):

  return 2*x + 2*y + 2*z

def Derfz(x,y,z):

  return 3*x**2 - 1

""" applying Newton method  """

def Newton(w,epsilon,max_iter):

    x,y,z = f(w)

    guesses=np.array([w])

    for n in range(0,max_iter):

        fx,fy,fz=f(np.array([x,y,z]))

        Dfx = Derfx(x,y,z)

        Dfy = Derfy(x,y,z)

        Dfz = Derfz(x,y,z)

        if Dfx == 0 or Dfy==0 or Dfz==0:

            print('Zero derivative, No solution found')

            return None

        x = x - fx/Dfx

        y=y-fy/Dfy

        z=z-fz/Dfz

        guesses=np.append(guesses,[[x,y,z]],axis=0)

    return guesses


w=np.array([1.,1.,1.])

guesses=Newton(w, 1e-10, 5) 

print("guesses : ")

print(guesses)

 

OUTPUT

 

Also Read: Write a program to add two polynomials
Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *