Question
I am trying to numerically solve a non linear system of algebraic equations using scipy.optimize.fsolve
.
I solve the system for several different values of its parameters (k1, k2, k3
below). For some values of the parameters fsolve
finds the correct solution, while for others the following warning is occurs
RuntimeWarning: The iteration is not making good progress, as measured by the
improvement from the last five Jacobian evaluations.
warnings.warn(msg, RuntimeWarning)
and from the result in these cases it is clear that something has gone wrong since h(result)
is not a vector of zeros.
There is no doubt about the fact that the solution does exist and it has nothing qualitatively different from those cases where the correct solution is found.
What is usually recommended in these cases? Is it an issue of initial conditions?
Examples
In the following I will show the idea of how I solve the system of equations:
import numpy as np
from scipy.optimize import fsolve
# Parameters for the system of equations
k1, k2, k3 = 2., 4.5, 0.1
# Function for evaluating the residual of the system
def h(x):
x1, x2, x3=x
eqn1 = k1*x1 + k2*x2**2 - x3
eqn2 = x1 - 2.*x2 + k3*x3
eqn3 = x1 + x2 + x3 - 1.
return eqn1, eqn2, eqn3
# An initial guess
x0 = np.array([1., 0.5, 1.])
# Get the solution of the system of equations
result = fsolve(h, x0=x0, xtol=1e-5)
# Now, verify that the solution is correct
print(h(result)) # Should be near (0,0,0)
This works great sometimes, but for some values of k1, k2, k3
it raises the RuntimeWarning
discussed above and returns the wrong result
# Bad parameters
k1, k2, k3 = 2., 4.5, -1.
# Bad result
result = fsolve(h, x0=x0, xtol=1e-5)
# Verification shows the residual is not near (0,0,0)
print(h(result))