How to include adjustable parameter in fsolve?

787 views Asked by At

I'm getting familiar with fsolve in Python and I am having trouble including adjustable parameters in my system of nonlinear equations. This link seems to answer my question but I still get errors. Below is my code:

 import scipy.optimize as so

 def test(x,y,z):
    
     eq1 = x**2+y**2-z
     eq2 = 2*x+1
    
     return [eq1,eq2]

     z = 1                                         # Ajustable parameter
     sol = so.fsolve(test , [-1,2] ,args=(z))      # Solution Array
     print(sol)                                    # Display Solution

The output gives

    TypeError: test() missing 1 required positional argument: 'z'

When z is clearly defined as an argument. How do I include this adjustable parameter?

1

There are 1 answers

0
t.o. On BEST ANSWER

So before posting here I should have spent a little bit more time playing with it. Here is what I found

import scipy.optimize as so
import numpy as np

def test(variables,z): #Define function of variables and adjustable arg
    
    x,y = variables     #Declare variables
    
    eq1 = x**2+y**2-1-z #Equation to solve #1
    eq2 = 2*x+1         #Equation to solve #2
    
    return [eq1,eq2]    #Return equation array

z = 1                                       #Ajustable parameter
initial = [1,2]                             #Initial condition list                          
sol = so.fsolve(test , initial, args = (z)) #Call fsolve
print(np.array(sol))                        #Display sol  

With an output

[-0.5         1.32287566]

I'm not the best at analyzing code, but I think my issue was that I had mixed up my variables and arguments in test(x,y,z) such that it didn't know what I was trying to apply the initial guess to.

Anyway, I hope this helped someone.

edit: While I'm here, the test function is a circle of adjustable radius and a line that intersects it at two points.

Red: x^2+y^2-2, Blue: 2x+1

If you wanted to find the positive and negative solutions, you'd need to pass your initial guess in as an array (someone asked a similar question here). Here is the updated version

z = 1
initial = [[-2,-1],[2,1]]
sol = []                            
for i in range(len(initial)): 
   sol.append(so.fsolve(test , initial[i], args = (z))) 
print(np.array(sol)) 

The output is

[[-0.5        -1.32287566]
 [-0.5         1.32287566]]