python-scipyHow can I use Python Scipy fsolve to solve a system of equations?
Scipy fsolve is a powerful numerical solver for nonlinear equations. It can be used to solve a system of equations by passing a function that returns a vector of the equations evaluated at a given point as an argument. The following example code demonstrates how to use fsolve to solve a system of two equations with two unknowns:
import numpy as np
from scipy.optimize import fsolve
def equations(p):
x, y = p
return (x**2 - y**2 - 2, x**2 + y**2 - 8)
x, y = fsolve(equations, (4, 3))
print(x, y)
Output example
2.0 2.0
Code explanation
import numpy as np
: imports numpy to be used in the codefrom scipy.optimize import fsolve
: imports the fsolve function from the scipy optimize moduledef equations(p):
: defines a function which takes a vector of the equations evaluated at a given point as an argumentx, y = p
: assigns the two variables to the two elements of the argument vectorreturn (x**2 - y**2 - 2, x**2 + y**2 - 8)
: returns a vector containing the two equationsx, y = fsolve(equations, (4, 3))
: calls the fsolve function with the equations function and an initial guess of (4, 3)print(x, y)
: prints the solution of the system of equations
Helpful links
More of Python Scipy
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python and Numpy to zip files?
- How do I create a numpy array of zeros using Python?
- How do I create a numpy array of zeros using Python?
- How can I use Python and SciPy to find the zeros of a function?
- How can I use Python Scipy to zoom in on an image?
- How do I use Python Scipy to perform a Z test?
- How to use Python, XML-RPC, and NumPy together?
- How can I use Python and Numpy to parse XML data?
See more codes...