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.
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.302776guess [-1, 1]x = -1.517490, y = 1.302776Numbers instead of formulas
Découvrez Solve Nonlinear Equations with SciPy fsolve avec un exemple pratique modifiable et exécutable en ligne.
Points clés
- 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.
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)
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.
- 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.
Leçon terminée ?
Marquez-la comme apprise pour suivre votre progression.
Votre progression est enregistrée dans ce navigateur Connectez-vous pour la garder sur tous vos appareils.
Outils pour cette leçon
- Traceur de courbes en ligne : tracer des points et des fonctionsTracez des points, un tableau collé ou des fonctions comme sin(x) en ligne et téléchargez le graphique en PNG. Traceur gratuit qui vous donne aussi le code Python avec Matplotlib.
- Basthon, Capytale ou CodeUtility : quel outil pour Python en ligne ?Basthon, Capytale et CodeUtility comparés pour écrire du Python en ligne au lycée : à quoi sert chaque outil, compte, débogueur, exercices et classes.
- Exercices Python corrigés : s'entraîner en ligne gratuitementExercices Python corrigés pour débutants et défis vérifiés automatiquement, du plus facile au plus difficile. À faire dans le navigateur, sans installation.