ziulfer
ziulfer

Reputation: 1369

Is fsolve good to any system of equations?

I don't have a lot of experience with Python but I decided to give it a try in solving the following system of equations:

x = A * exp (x+y)

y = 4 * exp (x+y)

I want to solve this system and plot x and y as a function of A.

I saw some a similar question and give fsolve a try:

`from scipy.optimize import fsolve
 def f(p):
   x, y = p
   A = np.linspace(0,4)
   eq1= x -A* np.exp(x+y)
   eq2= y- 4* np.exp(x+y)
   return (eq1,eq2)
 x,y =  fsolve(f,(0, 0))
 print(x,y)
 plt.plot(x,A)
 plt.plot(y,A)
`

I'm getting these errors: setting an array element with a sequence. Result from function call is not a proper array of floats.

Upvotes: 1

Views: 766

Answers (1)

Siva-Sg
Siva-Sg

Reputation: 2821

Pass the value of A as argument to the function and run fsolve for each value of A separately. Following code works.

from scipy.optimize import fsolve
import matplotlib.pyplot as plt
import numpy as np
def f(p,*args):
  x, y = p
  A = args[0] 

  return (x -A* np.exp(x+y),y- 4* np.exp(x+y))
A = np.linspace(0,4,5)
X = []
Y =[]
for a in A:
  x,y =  fsolve(f,(0.0, 0.0) , args=(a))
  X.append(x)
  Y.append(y)
  print(x,y)

plt.plot(A,X)
plt.plot(A,Y)

4.458297786441408e-17 -1.3860676807976662
-1.100088440495758 -0.5021704548996653
-1.0668987418054918 -0.7236105952221454
-1.0405000943788385 -0.9052366768954621
-1.0393471472966025 -1.0393471472966027
/usr/local/lib/python3.6/dist-packages/scipy/optimize/minpack.py:163: RuntimeWarning: The iteration is not making good progress, as measured by the 
  improvement from the last ten iterations.
  warnings.warn(msg, RuntimeWarning)
/usr/local/lib/python3.6/dist-packages/scipy/optimize/minpack.py:163: RuntimeWarning: The iteration is not making good progress, as measured by the 
  improvement from the last five Jacobian evaluations.
  warnings.warn(msg, RuntimeWarning)
[<matplotlib.lines.Line2D at 0x7f4a2a83a4e0>]

enter image description here

Upvotes: 4

Related Questions