scipy minimize with sqrt in objective function
I’m having trouble when using scipy minimize. I have sqrt in my objective function, it seems it does not work with minimize, I’m getting ValueError: Objective function must return a scalar.
Minimum code to reproduce the problem:
import scipy
from scipy.optimize import minimize
func = lambda x: (-24.9 * x[0] -25.0435945 * x[1] +24.9563343 * sqrt(1 - x[1]**2))**2 + (25.0627089 * x[0] -24.9563293 * x[1] -25.0435896 * sqrt(1 - x[1]**2))**2
res = minimize(func, (0.0, 0.0), method='SLSQP')
Also, if I’m using BFGS method, I’m getting TypeError: float() argument must be a string or a number.
How to get rid of these errors?
Maybe the problem is that it's trying to take square roots of some negative numbers? I added
from numpy import sqrt as sqrtn
and replacedsqrt
withsqrtn
in your function, and it "terminated successfully" but also said "RuntimeWarning: invalid value encountered in sqrt".By the way, the original version gives me "ValueError: math domain error", not "ValueError: Objective function must return a scalar". What version of Sage are you using?
Finally, this doesn't work for me in plain Python: it looks like a
scipy
problem, not particularly a SageMath problem.Thanks,
sqrtn
seems to work for me. I guess bounds are needed to avoid Invalid value, but it works even without bounds with my original function. I'm using version 8.1Version 8.1 of Sage??? That's from 2017. You should definitely upgrade.