- you take the square-root of a negative number (sqrt(x) with x negative)
- you exponentiate a negative number (x^a with x negative)
- you take the logarithm of a negative number (log(x) with x negative)
- or similar operations with functions that give complex results ...
Fsolve produces comlex numbers
1 vue (au cours des 30 derniers jours)
Torsten le 29 Mai 2023
Modifié(e) : Torsten le 29 Mai 2023
The usual reasons why solvers like "fsolve" produce complex numbers are:
John D'Errico le 29 Mai 2023
Remember that fsolve does not allow constraints. Not even bound constraints. So when one of the variables tries to go into a bad place, where, perhaps you are taking the sqrt of a negative number, then complex results start getting created. That commonly happens when a log, a sqrt, a fractional power are applied to a negative number. But other operations surely cause problems of this sort too.
I would strongly suggest you learn to use the debugger. Use it to watch your objective function, and see when something strange happens.
You might decide to set breakpoints in your function. Or, you might just decide to dump the current set of parameters at each iteration to the command window, as well as the objective. Watch for when a problem arises, and you will see that what we have said is surely true.
Can you stop fsolve from going to the bad places in your parameter space? Sadly, no. You can use other optimizers. But even there, you need to know where it is trying to go, and what constraints you need to apply. You can also decide to transform the parameters, to avoid the problem from happening. Of course, since we don't see any code, it becomes impossible to offer any useful help.