Solving math equation with Scipy

Before begin #

Make sure you install SciPy.

Interaction with Numpy #

Scipy builds on Numpy, and for all basic array handling needs you can use Numpy functions:

import numpy as np
np.some_function()

Solve a linear matrix equation using numpy #

numpy.linalg.solve(a, b) computes the exact solution of the well determinded linear matrix equation ax = b

  • Parameters:

    • a: coefficient matrix
    • b: ordinate of dependent variable values
  • Return:

    • x: solution of the system ax = b
  • Raise:

    • LinAlgError: if a is singular or not square

Examples:

Solve the system of equations 5 * x0 + 2 * x1 = 15 and 3 * x0 + 7 * x1 = 20:

import numpy as np
a = np.array([[5,3], [2,7]])
b = np.array([15,20])
x = np.linalg.solve(a, b)
print(x)
# Check it
np.allclose(np.dot(a, x), b)

Out:

[1.55172414 2.4137931 ]
True

Nonlinear root finding with SciPy #

scipy.optimize.fsolve(func, x0, args=(), fprime=None, full_output=0, col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, epsfcn=None, factor=100, diag=None)

Find the roots of a function.

Return the roots of the (non-linear) equations defined by func(x) = 0 given a starting estimate.

Example: Solve the following system: y - x^2 = 7 - 5x and 4y - 8x = -21

Solution with fsolve

from scipy.optimize import fsolve

def equations(p):
    x, y = p
    return (y - x**2 -7 + 5*x, 4*y - 8*x + 21)

x, y =  fsolve(equations, (5, 5))
print(equations((x, y)))
print(x)
print(y)

Out:

(0.0, 0.0)
3.5000000414181831
1.7500000828363667

Tags:

Python