NumPy Linear Systems
np.linalg.solve finds a solution to a square full-rank linear system. Prefer solving directly to explicitly calculating an inverse and multiplying by it.
How it works
The coefficient matrix describes how unknown quantities combine into observations. Verify the input shapes and check A @ x against b with a meaningful tolerance. A singular matrix has no unique solution under this contract, while an ill-conditioned matrix can amplify small input errors even when a solver returns a result. A successful call is therefore not a complete accuracy assessment.
Run the code
Select Try in playground to preload the complete code into the NumPy editor. Nothing executes on import; choose Run when ready. The first execution loads the local Pyodide runtime and NumPy package. Each ordinary run starts fresh, with no access to this page’s cookies or personal files. In-memory streams and temporary virtual files belong to the runtime, not your PC.
For local work, use a separate virtual environment and run python linear-systems.py. Download the complete source. The reviewed local environment uses Python 3.12.14 and NumPy 2.5.4; the browser uses Pyodide 0.27.7 with NumPy 2.0.2. Compatible examples are checked in both. See the environment setup. No Apache or database server is required.
Example
import numpy as np
a = np.array([[2., 1.], [1., 1.]])
b = np.array([8., 5.])
x = np.linalg.solve(a, b)
print(np.allclose(x, [3., 2.], atol=1e-12))
print(np.allclose(a @ x, b, atol=1e-12))
singular = np.array([[1., 1.], [2., 2.]])
if np.linalg.matrix_rank(singular) < singular.shape[0]:
print("Rejected singular system")
else:
np.linalg.solve(singular, b)
Expected result
True True Rejected singular system
The known solution and its reconstructed observations both pass. An explicit rank check rejects the dependent rows before solving, because the reviewed browser backend does not raise the same singular-solve exception as the local build. Numerical rank uses a tolerance; also inspect conditioning, finite results and residuals for less obvious cases.
Use NumPy’s official reference for precise contracts, supported versions and numerical limitations.