Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python math libraries extend the language's built-in numbers with arrays, symbolic algebra, and arbitrary-precision arithmetic. A computer algebra system keeps expressions exact rather than rounding each step to a floating-point value. These libraries let researchers, engineers, and AI agents run numerical and symbolic calculations in Python.
Popularity
NumPy has the most monthly downloads in this comparison, at 1.1B.
def row_norms(X, squared=False):
"""Row-wise (squared) Euclidean norm of X.
Equivalent to np.sqrt((X * X).sum(axis=1)), but also supports sparse
matrices and does not create an X.shape-sized temporary.
Performs no input validation.
Parameters
---------- X : array-like
The input array.
squared : bool, default=False
If True, return squared norms.
Returns
------- array-like
The row-wise (squared) Euclidean norm of X.
"""
if sparse.issparse(X):
X = X.tocsr()
norms = csr_row_norms(X)
if not squared:
norms = np.sqrt(norms)
else:
xp, _ = get_namespace(X)
if _is_numpy_namespace(xp):
X = np.asarray(X)
norms = np.einsum("ij,ij->i", X, X)
norms = xp.asarray(norms)
else:
norms = xp.sum(xp.multiply(X, X), axis=1)
if not squared:
norms = xp.sqrt(norms)
return norms
SciPy
Provides numerical algorithms and scientific-computing tools built on NumPy.
Downloads / mo
392.1M
Stars
15.2K
Last release
1.18.1
License
BSD-3-Clause
Strengths
Integrates callable functions.Use quad to compute a definite integral of a callable.
Approximates callable derivatives.Use differentiate.derivative to estimate a callable’s derivative.
Limitations
Sharp features can be missed.Pulses narrow relative to the integration interval can be integrated incorrectly.
Returned errors are estimates.Treat quad’s reported absolute error as an estimate.
import numpy as np
a = np.array([[3, 2, 0], [1, -1, 0], [0, 5, 1]])
b = np.array([2, 4, -1])
from scipy.linalg import solve
x = solve(a, b)
x
a @ x == b
def scipy_spsolve(A, b):
logger.debug("Scipy Solver - Solving linear system with scipy.sparse.linalg.spsolve")
indptr, indices, data = A.getValuesCSR()
Asp = scipy.sparse.csr_matrix((data, indices, indptr))
# SciPy's spsolve uses UMFPACK only when scikits.umfpack is installed and # applicable; otherwise it falls back to SuperLU. x = scipy.sparse.linalg.spsolve(Asp, onp.array(b))
# TODO: try https://jax.readthedocs.io/en/latest/_autosummary/jax.experimental.sparse.linalg.spsolve.html # x = jax.experimental.sparse.linalg.spsolve(av, aj, ai, b) logger.debug("Scipy Solver - Finished solving, linear solve res = %.3g",
np.linalg.norm(Asp @ x - b))
return x
def focus_of_attention(poses: Float[Tensor, "*num_poses 4 4"], initial_focus: Float[Tensor, "3"]) -> Float[Tensor, "3"]:
"""Compute the focus of attention of a set of cameras. Only cameras
that have the focus of attention in front of them are considered.
Args:
poses: The poses to orient.
initial_focus: The 3D point views to decide which cameras are initially activated.
Returns:
The 3D position of the focus of attention.
"""
# References to the same method in third-party code: # https://github.com/google-research/multinerf/blob/1c8b1c552133cdb2de1c1f3c871b2813f6662265/internal/camera_utils.py#L145 # https://github.com/bmild/nerf/blob/18b8aebda6700ed659cb27a0c348b737a5f6ab60/load_llff.py#L197 active_directions = -poses[:, :3, 2:3]
active_origins = poses[:, :3, 3:4]
# initial value for testing if the focus_pt is in front or behind focus_pt = initial_focus
# Prune cameras which have the current have the focus_pt behind them. active = torch.sum(active_directions.squeeze(-1) * (focus_pt - active_origins.squeeze(-1)), dim=-1) > 0
done = False
# We need at least two active cameras, else fallback on the previous solution. # This may be the "poses" solution if no cameras are active on first iteration, e.g. # they are in an outward-looking configuration. while torch.sum(active.int()) > 1 and not done:
active_directions = active_directions[active]
active_origins = active_origins[active]
# https://en.wikipedia.org/wiki/Line–line_intersection#In_more_than_two_dimensions m = torch.eye(3) - active_directions * torch.transpose(active_directions, -2, -1)
mt_m = torch.transpose(m, -2, -1) @ m
focus_pt = torch.linalg.inv(mt_m.mean(0)) @ (mt_m @ active_origins).mean(0)[:, 0]
active = torch.sum(active_directions.squeeze(-1) * (focus_pt - active_origins.squeeze(-1)), dim=-1) > 0
if active.all():
# the set of active cameras did not change, so we're done. done = True
return focus_pt
Dask
Runs PyData workloads in parallel with task scheduling.
def fit_transform(self, X, y=None):
"""Fit model to X and perform dimensionality reduction on X.
Parameters
---------- X : array-like, shape (n_samples, n_features)
Training data.
y : Ignored
Returns
------- X_new : array, shape (n_samples, n_components)
Reduced version of X. This will always be a dense array, of the
same type as the input array. If ``X`` was a ``dask.array``, then
``X_new`` will be a ``dask.array`` with the same chunks along the
first dimension.
"""
X = self._check_array(X)
if self.algorithm not in {"tsqr", "randomized"}:
raise ValueError(
"`algorithm` must be 'tsqr' or 'randomized', not '{}'".format(
self.algorithm
)
)
if self.algorithm == "tsqr":
u, s, v = da.linalg.svd(X)
u = u[:, : self.n_components]
s = s[: self.n_components]
v = v[: self.n_components]
else:
u, s, v = da.linalg.svd_compressed(
X, self.n_components, n_power_iter=self.n_iter, seed=self.random_state
)
if not DASK_2_26_0:
u, v = svd_flip(u, v)
X_transformed = u * s
explained_var = X_transformed.var(axis=0)
full_var = X.var(axis=0).sum()
explained_variance_ratio = explained_var / full_var
if self.compute:
v, explained_var, explained_variance_ratio, s = compute(
v, explained_var, explained_variance_ratio, s
)
self.components_ = v
self.explained_variance_ = explained_var
self.explained_variance_ratio_ = explained_variance_ratio
self.singular_values_ = s
self.n_features_in_ = X.shape[1]
return X_transformed
def _evaluate(self):
import numexpr as ne
# convert the expression to a valid numexpr expression s = self.convert()
env = self.expr.env
scope = env.full_scope
_check_ne_builtin_clash(self.expr)
return normalize_numexpr_result(ne.evaluate(s, local_dict=scope))
JAX
Differentiates, compiles, and transforms NumPy code.
def operator_to_matrix(operator_fn, problem):
"""Only used for when debugging.
Can be used to print the matrix, check the conditional number, etc.
"""
J = jax.jacfwd(operator_fn)(np.zeros(problem.num_total_dofs_all_vars))
return J
FAQ
NumPy suits numerical work on arrays and matrices. SciPy adds integration, optimization, and other scientific algorithms on top of NumPy arrays. SymPy suits exact symbolic math. mpmath suits arithmetic at arbitrary precision.
NumPy is the core package for array computing in Python, with broadcasting, elementwise functions, and linear algebra.
SymPy is a computer algebra system that keeps expressions exact and manipulates them symbolically. Its evalf method computes numerical approximations to a chosen number of digits.
NumPy supplies the array type and core numerical operations. SciPy builds on those arrays with algorithms for integration, differential equations, optimization, and signal processing.
JAX runs NumPy-style array code with automatic differentiation and compilation on supported accelerators.
For coding agents
Found your math library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.