0

How to solve a pair of nonlinear equations using Python? In this question a pair of nonlinear equations that each has two arguments were solved.

Now I have more than two equations, each has a number of arguments. The number of arguments is more than the number of equations.

By using the method in the question. eg:

'''
def func0(a,b,c,d,local1=α,local2=β):
    #process
    return function
# func0==0
def func1():
    return
#etc

def multi_equ(p):
    a,b,c,d,e = p
    return (func0(a,b,c,d,local1,local2),func1(c,d,e),func2(a,b,c,d,e,local),etc)
'''

My question is:

How to write the fsolve() to solve such function when, for example, sometime argument c is known, I am trying to solve the rests.

Zhidong Li
  • 61
  • 1
  • 9
  • fsolve() seems requiring some sense of order. I am thinking to write a wrap function changing the arguments order in multi_equ(). Is there a better way, or other function can replace fsolve()? – Zhidong Li Jun 07 '18 at 04:26

1 Answers1

0

In order to use fsolve, you need

A function that takes at least one (possibly vector) argument, and returns a value of the same length.

So, the number of equations must be equal to the number of unknowns. If you have a function that takes similar input, except that one of the input variables is known, then wrap it in another function, like this:

def f(a, b, c, d): 
    return [a-b, b-c, c-d] 

def func(p):
    a, b, d = p
    c = 0.5
    return f(a, b, c, d)

Here func is suitable to be used in fsolve, for example

fsolve(func, [0, 0, 0])   # returns [0.5, 0.5, 0.5]

Number of unknowns different from the number of equations

If the mathematical problems has more (or fewer) unknowns than equations, then fsolve cannot be used. The tool I would use then is least_squares which minimizes the sum of squares of func.

def func(p):
    a, b, c, d = p
    return [a-b, b-c, c-d] 

least_squares(func, [3, 2, 5, 1]) 

This finds a solution of least-squares problem as [2.75, 2.75, 2.75, 2.75]. It also returns the cost which, being nearly zero, tells us that func indeed turns to zero at the point that was found. This solution is not unique.