Math and Science with Python

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.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • Writing equations as a function that returns zeros
  • How the starting guess picks the root
  • Checking convergence with full_output
circle and parabola
guess [1, 1]x = 1.517490, y = 1.302776
guess [-1, 1]x = -1.517490, y = 1.302776

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

From a dark valley to code
equations(v)🗺️ How far you are from the answer
guess🔦 Where you start walking
fsolve(equations, guess)🚶 Walk until you reach a solution
ier == 1✅ The solver says it arrived
A starting point and a solver that walks downhill.
In one sentence

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

  1. Move everything to one side: x**2 + y**2 = 4 becomes x**2 + y**2 - 4.
  2. The function returns a list with one value per equation.
  3. Different guesses, [1, 1] and [-1, 1], find different crossings.
  4. full_output=True returns ier, 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.solve is exact and faster.
  • Equations SymPy can solve exactly: sympy.solve gives exact roots.

Example code

Open in editor →
main.py
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)
Get a Run button for this example

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.

  1. Change the function or the data and predict the result before running.
  2. Compare the numerical answer with the exact one from SymPy or a hand calculation.
  3. Plot the result with Matplotlib to see what the numbers mean.
Run in the Python compiler →

Common mistakes

Returning one combined value for a system

fsolve needs one value per equation; adding them hides which one is wrong.

Problem
return x**2 + y**2 - 4 + y - x**2 + 1
Fix
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.

Problem
root = fsolve(equations, guess)
Fix
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