0

I'm receiving an error with this simple code, the problem is that the error only appears with one of the equations that I need (78 * x**0.3 * y**0.8 - 376).

The error : invalid value encountered in double_scalars ; F[0] = 78 * x**0.3 * y**0.8 - 376

If I erase * y**0.8 from the first equation, the code runs perfectly, but obviously it doesn't work for me.

Code:

import numpy as np
from scipy.optimize import fsolve

def Funcion(z):
   x = z[0]
   y = z[1]

   F = np.empty((2))
   F[0] = 78 * x**0.3 * y**0.8 - 376
   F[1] = 77 * x**0.5 * y - 770
   return F

zGuess = np.array([1,1])
z = fsolve(Funcion,zGuess)
print(z)
Warren Weckesser
  • 110,654
  • 19
  • 194
  • 214
  • Does this answer your question? [Python scipy.optimize: Using fsolve with multiple first guesses](https://stackoverflow.com/questions/13057022/python-scipy-optimize-using-fsolve-with-multiple-first-guesses) – TheFaultInOurStars Apr 01 '21 at 00:48

2 Answers2

2

F[0] will be complex if y is negative. fsolve doesn't support complex root finding.

Ben
  • 46
  • 3
1

You need to solve the nonlinear equation system F(x,y) = 0 subject to x, y >= 0, which is equivalent to minimize the euclidean norm ||F(x,y)|| s.t. x,y >= 0. To solve this constrained optimization problem, you can use scipy.optimize.minimize as follows:

import numpy as np
from scipy.optimize import minimize

def Funcion(z):
   x = z[0]
   y = z[1]

   F = np.empty((2))
   F[0] = 78 * x**0.3 * y**0.8 - 376
   F[1] = 77 * x**0.5 * y - 770
   return F

# initial point
zGuess = np.array([1.0, 1.0])

# bounds x, y >= 0
bounds = [(0, None), (0, None)]

# Solve the constrained optimization problem
z = minimize(lambda z: np.linalg.norm(Funcion(z)), x0=zGuess, bounds=bounds)

# Print the solution
print(z.x)

joni
  • 6,840
  • 2
  • 13
  • 20