afg
afg

Reputation: 29

How do I use newtons method on python to solve a system of equations?

I have an assignment where I need to make a single defined function that runs newtons method and then be able plug in other defined functions to it and it will solve them all. I wrote one that works for equations that have 1 variable, and I only need to solve for one variable from the system but I don't know how to do that in code without solving for all four of them.

the function I wrote to run newtons method is this:

def fnewton(function, dx, x, n):
#defined the functions that need to be evaluated so that this code can be applied to any function I call
    def f(x):
        f=eval(function)
        return f
#eval is used to evaluate whatever I put in the function place when I recall fnewton
#this won't work without eval to run the functions
    def df(x):
       df=eval(dx)
       return df

    for intercept in range(1,n):
        i= x-(f(x)/df(x))
        x= i
#this is literally just newtons method
#to find an intercept you can literally input intercept in a for loop and it'll do it for you
#I just found this out
#putting n in the range makes it count iterations
print ('root is at')
print (x)
print ('after this many iterations:')
print (n)

my current system of equations function looks like this:

def c(x):
    T=x[0]
    y=x[1]
    nl=x[2]
    nv=x[3]

    RLN=.63*Antoine(An,Bn,Cn,T)-y*760
    RLH=(1-.63)*Antoine(Ah,Bh,Ch,T)-(1-y)*760
    N=.63*nl+y*nv-50
    H=(1-.63)*nl+(1-y)*nv-50
    return[RLN,RLH,N,H] 

To use my function to solve this I've entered multiple variations of:

fnewton("c(x)","dcdx(x)", (2,2,2,2), 10)

Do I need to change the system of equations into 1 equation somehow or something I don't know how to manipulate my code to make this work and also work for equations with only 1 variable.

Upvotes: 0

Views: 581

Answers (1)

Adrian Usler
Adrian Usler

Reputation: 81

To perform Newton's method in multiple dimensions, you must replace the simple derivative by a Jacobian matrix, that is, a matrix that has the derivatives of all components of your multidimensional function with respect to all given variables. This is decribed here: https://en.wikipedia.org/wiki/Newton%27s_method#Systems_of_equations, (or, perhaps more helpful, here: https://web.mit.edu/18.06/www/Spring17/Multidimensional-Newton.pdf in Sec. 1.4)

Instead of f(x)/f'(x), you need to work with the inverse of the Jacobian matrix times the vector function f. So the formula is actually quite similar!

Upvotes: 1

Related Questions