Solve Nonlinear Equations in Python with SciPy fsolve
Find where a system of nonlinear equations equals zero with scipy.optimize.fsolve, starting from a guess.
- Writing equations as a function that returns zeros
- How the starting guess picks the root
- Checking convergence with full_output
guess [1, 1]x = 1.517490, y = 1.302776guess [-1, 1]x = -1.517490, y = 1.302776Numbers instead of formulas
The problem
Many equations have no formula for their solution: where a circle crosses a parabola, the angle in a projectile problem, or cos(x) = x. A numerical solver finds the answer to as many digits as you need.
Think of it like this
fsolve is like searching for the lowest spot in a dark valley with a torch. Where you start walking decides which dip you end up in, so different starting guesses can find different solutions.
equations(v)🗺️ How far you are from the answerguess🔦 Where you start walkingfsolve(equations, guess)🚶 Walk until you reach a solutionier == 1✅ The solver says it arrivedscipy.optimize.fsolve(func, x0) finds the values where func returns zeros, starting from the guess x0. For a system, func takes a list of unknowns and returns one value per equation.
Key points
- Move everything to one side:
x**2 + y**2 = 4becomesx**2 + y**2 - 4. - The function returns a list with one value per equation.
- Different guesses,
[1, 1]and[-1, 1], find different crossings. full_output=Truereturnsier, which is 1 when the solver converged.
When should you use it?
- Intersection points of curves.
- Equilibrium and steady-state problems in physics and chemistry.
- Equations with no closed-form solution, like
cos(x)= x.
When not to use it
- Linear systems:
np.linalg.solveis exact and faster. - Equations SymPy can solve exactly:
sympy.solvegives exact roots.
Example code
import numpy as np
from scipy.optimize import fsolve
# Solve the system
# x**2 + y**2 = 4 (a circle)
# y = x**2 - 1 (a parabola)
def equations(v):
x, y = v
return [x**2 + y**2 - 4, y - x**2 + 1]
# fsolve needs a starting guess; different guesses find different roots
for guess in ([1, 1], [-1, 1]):
root = fsolve(equations, guess)
print(f"guess {guess} -> x = {root[0]:.6f}, y = {root[1]:.6f}")
print(" both equations hold:", np.allclose(equations(root), 0))
# One equation in one unknown: cos(x) = x
root = fsolve(lambda x: np.cos(x) - x, 1.0)[0]
print(f"cos(x) = x at x = {root:.6f}")
# full_output tells you whether it converged
root, info, ier, message = fsolve(equations, [1, 1], full_output=True)
print("Converged:", ier == 1)
Result of running the code
guess [1, 1] -> x = 1.517490, y = 1.302776
both equations hold: True
guess [-1, 1] -> x = -1.517490, y = 1.302776
both equations hold: True
cos(x) = x at x = 0.739085
Converged: True
Code explanation
equations() returns the left sides of both equations moved to the form ... = 0, so fsolve looks for the x and y that make both values 0. The circle and the parabola cross twice, and the guesses [1, 1] and [-1, 1] lead to the two crossings at x = 1.517490 and x = -1.517490. np.allclose checks that both equations really hold there. fsolve also solves the single equation cos(x) = x, and full_output=True returns ier, which is 1 when the solver converged.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Returning one combined value for a system
fsolve needs one value per equation; adding them hides which one is wrong.
return x**2 + y**2 - 4 + y - x**2 + 1
return [x**2 + y**2 - 4, y - x**2 + 1]
Trusting the result without checking
fsolve can stop without converging; check the equations at the result.
root = fsolve(equations, guess)
root = fsolve(equations, guess)
print(np.allclose(equations(root), 0))
Finished this lesson?
Mark it as learned to track your progress.
Tools for this lesson
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.
- NumPy Online: Run NumPy Code in Your BrowserA NumPy playground with no install: arrays, statistics, linear algebra, random numbers and broadcasting. NumPy 2, pandas and SciPy ready to import.