# 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?

edit retag close merge delete

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 replaced sqrt with sqrtn in your function, and it "terminated successfully" but also said "RuntimeWarning: invalid value encountered in sqrt".

( 2023-10-18 19:22:48 +0100 )edit

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?

( 2023-10-18 19:29:20 +0100 )edit

Finally, this doesn't work for me in plain Python: it looks like a scipy problem, not particularly a SageMath problem.

( 2023-10-18 19:29:59 +0100 )edit

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.1

( 2023-10-19 07:44:09 +0100 )edit

Version 8.1 of Sage??? That's from 2017. You should definitely upgrade.

( 2023-10-19 18:32:42 +0100 )edit