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.

  • Intermédiaire
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • 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

Découvrez Solve Nonlinear Equations with SciPy fsolve avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  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.

Quand l’utiliser ?

  • Solve equations, integrals and differential equations in a few lines.
  • Fit models to measured data and analyse signals in science and engineering classes.
  • Check homework answers numerically and see where a hand calculation went wrong.

Code d’exemple

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)
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

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

Explication du code

Cet exemple montre Solve Nonlinear Equations with SciPy fsolve en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  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.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

Outils pour cette leçon