0
0
NumPydata~5 mins

np.linalg.solve() for linear systems in NumPy

Choose your learning style9 modes available
Introduction

We use np.linalg.solve() to find the values of unknowns in a set of linear equations quickly and accurately.

When you have multiple linear equations and want to find the values of variables.
When solving real-world problems like mixing chemicals in exact proportions.
When calculating forces in a structure with multiple supports.
When balancing financial equations with several unknown amounts.
Syntax
NumPy
np.linalg.solve(A, b)

A is a square matrix representing coefficients of variables.

b is a vector or matrix representing the constants on the right side of equations.

Examples
Solves two equations with two unknowns.
NumPy
import numpy as np
A = np.array([[3,1],[1,2]])
b = np.array([9,8])
x = np.linalg.solve(A, b)
print(x)
Solves three equations with three unknowns.
NumPy
import numpy as np
A = np.array([[1,2,3],[0,1,4],[5,6,0]])
b = np.array([14,13,23])
x = np.linalg.solve(A, b)
print(x)
Sample Program

This program solves two linear equations with two unknowns and prints the values of x and y.

NumPy
import numpy as np

# Coefficients matrix for equations:
# 2x + 3y = 8
# 5x + 4y = 13
A = np.array([[2, 3], [5, 4]])

# Constants vector
b = np.array([8, 13])

# Solve for x and y
solution = np.linalg.solve(A, b)

print('Solution for x and y:', solution)
OutputSuccess
Important Notes

The matrix A must be square (same number of rows and columns).

If A is singular (no unique solution), np.linalg.solve() will raise an error.

Use this method instead of manual calculations for accuracy and speed.

Summary

np.linalg.solve() finds unknown values in linear equations.

It needs a square matrix of coefficients and a constants vector.

It returns the solution vector with values of the unknowns.