Determinants: signed volume
Interpret the determinant as a signed volume scale, characterize it axiomatically, derive the product rule and compute it stably with LU and logarithms. Explain why determinant size does not measure proximity to singularity, and connect it to Gaussian densities, normalizing flows and log-determinant derivatives.
After this lesson you can
- Interpret the determinant as oriented volume and reason about its sign.
- Deduce determinant properties from multilinearity and alternation.
- Prove det(AB) = det(A) det(B) using elementary matrices.
- Compute determinants and log determinants stably from an LU factorization.
- Explain why a small determinant does not imply a matrix is close to singular.
Before you start
Motivation: three questions, one number
A square matrix is a linear map from to itself, and raises three seemingly independent questions:
- How much does it change volumes? The unit cube becomes a parallelepiped. What is its volume?
- Does it preserve orientation? Or does it flip space, like a mirror turning a right hand into a left hand?
- Can it be undone? Does the inverse exist?
The determinant answers all three with one number: is the volume multiplier, its sign says whether orientation is preserved, and if and only if is invertible. It is no accident that one number summarizes so much: a map collapsing space to lower dimension leaves zero volume and cannot be undone, and changing from preserved to reversed orientation requires passing through that collapse.
Probabilistic models encounter it constantly, usually as a logarithm:
- The multivariate Gaussian. The density of at is
Factor corrects volume. If with and , the point cloud of occupies times more volume, and density falls proportionally (see the full multivariate Gaussian definition).
- Normalizing flows. A generative model transforming data into noise via a differentiable bijection obtains exact likelihood using . Much of architecture design makes that determinant cheap (normalizing flows).
- Gaussian processes. Fitting kernel hyperparameters maximizes , the marginal likelihood. With a few hundred points no longer fits in a floating-point number; its logarithm does.
- Training any such model requires differentiating with respect to . Result follows in this lesson from the cofactor formula.
This review has two goals: understand the determinant as oriented volume, from which all its properties follow, and calculate it well, which in practice means computing its logarithm from a factorization. One warning matters from the start: determinant does not measure how close a matrix is to singular.
Intuition: the area scale factor
Start in the plane. Columns of are basis images and , so the unit square with vertices maps to the parallelogram with vertices . What is its area?
Base times height, calculated in a way that later generalizes. If , apply vertical shear with to the plane. It slides each vertical segment along its line without stretching, so by Cavalieri’s principle it changes no figure’s area. It maps to on axis , and to . The transformed parallelogram has base on the axis and height :
If , base is already vertical, height is horizontal distance , and area is , as the same formula gives. The shear is exactly the first step of Gaussian elimination: subtract times row 1 from row 2. You will return to it when calculating determinants.
The number without absolute value, , is the determinant of , and its sign has meaning: positive when the shortest rotation from to is counterclockwise, like that from to , and negative when clockwise. Try it.
What you should have seen:
- The sign changes only when crossing the line of . On the line the parallelogram is a segment and : columns are dependent and collapses the plane to a line. Changing sign continuously requires passing through this collapse.
- Shears change nothing. Sliding parallel to changes neither base nor height. In formulas, .
- Swapping columns changes sign while preserving area: rotation from to reverses. Negating one column also reverses orientation.
- Signed base times height. With fixed, , where is the distance of from the line of , positive on its left. This signed distance is a linear function of : its dot product with the unit vector perpendicular to . That is why determinant is linear in each column.
The unit square is not special. A linear map takes a square of side with vertex to parallelogram , a translated and reduced copy of the previous one, of area . Approximate any region by squares on increasingly fine grids; each scales by the same factor and
The unit disk, for example, becomes an ellipse of area ; the lab checks this by Monte Carlo.
In three dimensions and beyond
In columns of generate parallelepiped , the image of unit cube . Its volume is , and the sign of again describes orientation: in positive if is a right-handed triple, like (right-hand thumb, index and middle finger), negative if left-handed. See it before formalizing.
Three observations the rest of the lesson turns into theorems:
- Determinant is linear in each column. Replacing with , with in the plane of and , changes signed volume to : a line in crossing zero and continuing to the other side.
- Zero volume is equivalent to noninvertibility. At all 600 points fall onto a plane and distinct points reach the same location: cannot be recovered from .
- Density is divided by . The same points occupy times more volume. If has density and is invertible, has density : the linear case of the density change-of-variables formula used in normalizing flows.
Three axioms determine everything
What properties does signed parallelepiped volume have as a function of its edges? Those just observed:
- It scales with each edge. Doubling an edge doubles volume, and negating it reverses orientation. Addition is respected too: with other edges fixed, volume is the unchanged base times signed height of the moving edge, and that height is a linear function of it.
- Swapping two edges reverses orientation. rotates opposite to .
- The unit cube has volume 1.
Remarkably, these three properties suffice: no other function satisfies them.
Everything else follows. The first two consequences appeared in the interactive; prove them yourself.
Step 1 of 4. Suppose columns and , with , are identical. What does antisymmetry say?
Proof
1. Some column is a combination of the others, . By linearity in column , , where in summand column occupies position . Each summand has two identical columns, at positions and , and is 0.
2. Let be upper triangular. If some , the first columns are zero from row onward: vectors in the subspace spanned by of dimension , hence dependent and . If all are nonzero, traverse columns left to right and subtract from column multiples of earlier columns (already reduced to ) to zero entries above its diagonal. By exercise part (b), is unchanged and we reach . Linearity pulls each out: . For lower triangular matrices do the same right to left.
∎Leibniz’s formula and uniqueness
Multilinearity fully expands . Try predicting each step before revealing it.
The last step uses the sign of a permutation, with the number of inversions of , well defined even though a permutation may be written as a product of transpositions in many ways.
Proof
Uniqueness. The derivation above used only the axioms, so any satisfying them is this formula.
Existence (outline). Check that the formula satisfies the axioms. It is multilinear because each term contains exactly one factor from each column. It is normalized because at only the identity term survives. It is alternating: if is with columns and swapped and is the transposition , the term for in is the term for in with sign reversed, because . Since is a bijection of , .
∎For there are two permutations, identity and swap, giving : the signed area from the start. For there are six terms, three even and three odd (Sarrus’s rule):
For general there are terms with factors. The formula gives an explicit definition and a tool for proofs; as an algorithm, as you will see, it is useless.
The product rule
If multiplies areas by and then multiplies them by , the composition should multiply them by the product. The key is that scales any region by the same factor, including one already deformed by .
The proof uses the elementary matrices of Gaussian elimination. Multiplication on the left performs row operations; on the right, the same matrices perform analogous column operations: adds to column of column multiplied by .
Proof
There are three types of elementary matrix; in each case compare the effect on columns with the determinant of :
- Swap columns and : by antisymmetry, and .
- Scale column by : by linearity, and because is diagonal.
- Add to column times column : by the previous exercise, and because is triangular with ones on the diagonal.
Recall also from elimination that an invertible matrix reduces to using elementary operations, , and is therefore a product of elementary matrices, , since the inverse of an elementary matrix is another of the same type. You now have everything you need.
Step 1 of 4. Why split into two cases according to ?
The product rule has many immediate consequences:
- , from .
- even if , as seen in the interactive.
- The determinant is basis-independent. Similar matrices have the same determinant: . Thus it makes sense to speak of the determinant of a linear map , just as of its trace.
- . This follows not from the product rule but multilinearity: multiplies each of the columns.
One property remains hidden in the interactive: it treats rows like columns.
Proof
By Leibniz’s formula, . Changing the product index to gives . Since is a bijection of and , the sum is exactly that for .
∎Consequently, everything said about columns holds for rows: swapping two rows changes the sign, adding a multiple of another row leaves the determinant unchanged, and a zero row makes it zero. These are exactly the Gaussian elimination operations. Another consequence: if is orthogonal, gives , and . Orthogonal matrices preserve volumes, and the sign distinguishes rotations () from those involving a reflection (), such as Householder reflections.
Proof
(i) ⇒ (ii): . (ii) ⇒ (iii): if the rank were less than , the columns would be dependent and . (iii) ⇔ (iv) by the rank-nullity theorem, and (iii) and (iv) together say is surjective and injective, i.e. (i).
∎Calculation: pivots, not permutations
Leibniz’s formula has terms of factors. Cofactor expansion, seen in the next section, merely groups them differently and has the same order of cost. With there are million terms; with , , and at one billion terms per second it would take about 77 years. Even a small model’s covariance matrix has in the hundreds.
Gaussian elimination solves the problem. LU factorization with partial pivoting gives , where is a permutation matrix, is lower triangular with ones on its diagonal, and is upper triangular. Since and , the product rule gives
If elimination made row swaps, is a product of transpositions and , which is its own inverse. Hence
the product of pivots with the sign from swaps, at a cost of about operations: with , fewer than , a fraction of a second. Geometrically, elimination simply repeats the shear from the beginning.
The log-determinant
Computing determinants accurately has a second difficulty: the number itself. A float64 represents magnitudes up to about , and the smallest normal numbers are around (below these are subnormal numbers with decreasing precision, down to about ; see floating-point representation). A product of hundreds of pivots easily escapes that range: rounds to and to , even for these innocuous matrices. Hence we work with the log-determinant:
This is what np.linalg.slogdet returns, and what Gaussian density, Gaussian-process likelihood and flow likelihood need, since they use only . When the matrix is symmetric positive definite, such as a covariance or kernel matrix, Cholesky factorization is even better: no pivoting, half the cost, and .
Cofactors, adjugate and Cramer’s rule
Explicit determinant and inverse formulas are useful for reasoning and differentiation rather than computation. The minor is the determinant of matrix obtained by removing from row and column ; the cofactor is .
Proof
Write column as . By linearity in that column, , where is with column replaced by . Move that column to the first position with adjacent column swaps, and row to the first position with adjacent row swaps: the sign changes by , leaving a matrix whose first column is and whose lower-right block is the submatrix of , with rows and columns in the same order. Subtracting multiples of the first column from the others zeros the rest of the first row, and the function taking a matrix of size to the determinant of satisfies all three axioms, so it is . Hence . Row expansion follows by applying this to .
∎Proof
Entry of is : the row expansion of the determinant of the matrix obtained by replacing row of with its row . If , that matrix is and the sum is . If , it has two identical rows and the sum is 0. For reason similarly using columns.
∎For this is the familiar formula: .
Proof
Since , linearity in column gives , with in position . All terms with have two identical columns; what remains is .
∎What they are for. These formulas say that the entries of and of the solution of are quotients of polynomials in the entries of , so they depend continuously and differentiably on those entries while . They also give the determinant’s derivative. In the row expansion, , no cofactor depends on row , hence . Since the cofactor matrix is :
This is Jacobi’s formula, , generalized in matrix calculus (inverse and log-determinant derivatives) and used by autograd when training a flow or Gaussian-process hyperparameters. The absolute value is no obstacle: the derivative of is even for negative .
Why they are not used for computation. Cofactor expansion has factorial cost. Cramer’s rule needs determinants: even using LU this takes on the order of operations versus for one factorization and its two substitutions, and accumulates more rounding error. The adjugate inverse has the same problem. For and matrices, however, closed formulas are entirely reasonable and used daily in graphics and robotics.
The determinant as local volume scaling
Maps of practical interest are nonlinear, but look linear up close. If is differentiable at , then , where is the Jacobian matrix. A small cube with side around transforms almost into a parallelepiped, the image of under the linear part, with volume approximately . The Jacobian determinant is the local volume scaling factor.
Summing over an increasingly fine grid of small cubes gives the change-of-variables formula, which you will formalize in calculus (change of variables): if is a differentiable bijection with differentiable inverse from to ,
The classic example is polar coordinates, , with
and : this yields the used to calculate the Gaussian integral. For probability densities, if is such a bijection and , the probability mass of each small cube is preserved and , that is,
If , the chain rule makes a product of Jacobians and the product rule turns its log-determinant into a sum: , each evaluated at its intermediate point (log-determinants in composed transformations). A normalizing flow stacks dozens of such layers; the problem is that a general determinant of costs . RealNVP’s affine coupling layer (Dinh, Sohl-Dickstein and Bengio, 2016) avoids this: split and leave unchanged while transforming . Its Jacobian is block triangular, with and on the diagonal, so : linear cost, while and may be arbitrary neural networks. It is the third map in the interactive.
Cross product in ℝ³
In the determinant also produces a vector. This section writes the dot product as , the usual notation in this context.
The key identity follows by examining that expansion: the dot product with replaces the formal row by . Thus is the determinant of the matrix with rows ; by transposition it is also the determinant of the matrix with columns ; and since moving from to is an even cyclic permutation of three elements,
The scalar triple product is the signed volume of the parallelepiped. The full geometry of the cross product follows.
Proof
1. because two columns are identical, and likewise for .
3. With , , which is positive if ; this holds for independent by item 4.
4. If dependent, for all , hence for all and . If independent, add an to form a basis: and, by the identity above, .
2. If dependent, both quantities are 0. Otherwise, let . By the identity, . Now take an orthogonal matrix , with an orthonormal basis for the plane of and : in that basis, , and , so , with . The last factor is the signed area of the parallelogram measured in its plane, which does not distort. Taking absolute values, is that area.
∎The algebra also follows from the formal determinant. The cross product is bilinear and anticommutative, (swap two rows), and , , . It is not associative: , whereas . It satisfies Lagrange’s identity, , which with again gives .
It appears throughout three-dimensional geometry: a mesh triangle’s normal is , the torque of a force is , and the velocity of a point on a solid rotating with angular velocity is , a foundation of robot kinematics. In the plane its counterpart is the determinant itself: the sign of tells whether lies left or right of the line from to , the orientation test underlying computational geometry algorithms; the polygon area formula sums determinants of successive vertices.
What the determinant does not measure
It is tempting to read a small as “ is close to singular”. This fails in both directions.
- Tiny determinant, perfect matrix. has . But , solving divides each component by and loses no digits.
- Determinant 1, nearly singular matrix. The shear has determinant 1 for every , and with a perturbation of size makes it singular. Worse, the triangular matrix of size with ones on the diagonal and in every entry above it has determinant 1 for every , and with is numerically singular.
The explanation lies in singular values, which you will study with the SVD: with orthogonal gives . The spectral-norm distance from to the nearest singular matrix is (Eckart–Young theorem), and relatively , with the condition number. The determinant mixes size and shape: multiplying by multiplies by and leaves unchanged. In high dimension, is astronomical or tiny for almost any other than 1.
import numpy as np
print(" n det(U_n) σ_min(U_n) κ(U_n) det(0.1 I_n)")
for n in [5, 10, 20, 30, 60]:
U = np.eye(n) - np.triu(np.ones((n, n)), 1) # 1 en la diagonal, −1 por encima
s = np.linalg.svd(U, compute_uv=False)
print(f"{n:2d} {np.linalg.det(U):6.3f} {s[-1]:.3e} {s[0] / s[-1]:.3e} {0.1 ** n:.0e}")
# y el determinante de una matriz singular, en coma flotante, casi nunca es exactamente 0
rng = np.random.default_rng(1)
R1 = np.outer(rng.standard_normal(4), rng.standard_normal(4)) # rango 1
print("\ndet de una matriz 4×4 de rango 1:", np.linalg.det(R1), " rango numérico:", np.linalg.matrix_rank(R1))To decide whether a matrix is invertible in practice, inspect (with np.linalg.cond) or the numerical rank with tolerance relative to , not whether its determinant is small or exactly zero.
Implementation from scratch
The cells share a session: run them in order. The first implements the definition directly, with permutations and cofactors.
import numpy as np
from itertools import permutations
def sgn(p):
"""Signo de una permutación de (0, ..., n-1): (-1) elevado al número de inversiones."""
inv = sum(1 for i in range(len(p)) for j in range(i + 1, len(p)) if p[i] > p[j])
return -1 if inv % 2 else 1
def det_leibniz(A):
"""Suma de los n! términos sgn(σ) a[σ(0),0] a[σ(1),1] ... a[σ(n-1),n-1]."""
n = len(A)
total = 0.0
for p in permutations(range(n)):
term = float(sgn(p))
for j in range(n):
term *= A[p[j]][j]
total += term
return total
def det_cofactor(A):
"""Desarrollo por la primera columna, recursivo: la misma suma de n! términos, agrupada."""
n = len(A)
if n == 1:
return A[0][0]
total = 0.0
for i in range(n):
menor = [fila[1:] for k, fila in enumerate(A) if k != i] # sin la fila i ni la columna 0
total += (-1) ** i * A[i][0] * det_cofactor(menor)
return total
rng = np.random.default_rng(0)
A = rng.standard_normal((6, 6))
print(f"Leibniz (720 términos): {det_leibniz(A.tolist()):+.12f}")
print(f"cofactores: {det_cofactor(A.tolist()):+.12f}")
print(f"np.linalg.det: {np.linalg.det(A):+.12f}")Now for cost. Each extra multiplies the number of recursive calls by , so measured times let us predict the next ones.
import math, time
tiempos = {}
for n in [7, 8, 9]:
M = rng.standard_normal((n, n)).tolist()
t0 = time.perf_counter()
det_cofactor(M)
tiempos[n] = time.perf_counter() - t0
extra = f" ({tiempos[n] / tiempos[n - 1]:.1f} veces el de n = {n - 1})" if n > 7 else ""
print(f"n = {n}: {tiempos[n]:6.3f} s{extra}")
# el tiempo crece como n!: cada n más lo multiplica por n. Extrapolamos desde n = 9.
for n in [10, 12, 15, 20]:
seg = tiempos[9] * math.factorial(n) / math.factorial(9)
print(f"n = {n}: unos {seg:.1e} s = {seg / 3600:.1e} h = {seg / 3.156e7:.1e} años")The prediction for is a few seconds. The next cell checks it; it is excluded from automated tests precisely because it takes time.
M = rng.standard_normal((10, 10)).tolist()
t0 = time.perf_counter()
det_cofactor(M)
print(f"n = 10 medido: {time.perf_counter() - t0:.1f} s predicción: {tiempos[9] * 10:.1f} s")With , extrapolation gives tens or hundreds of thousands of years depending on the machine. The alternative is LU with partial pivoting, keeping track of swaps.
def lu_pivot(A):
"""PA = LU con pivoteo parcial. Devuelve perm (P como vector de índices), L, U y el número de intercambios."""
U = np.array(A, dtype=float)
n = U.shape[0]
L = np.eye(n)
perm = np.arange(n)
swaps = 0
for k in range(n - 1):
p = k + int(np.argmax(np.abs(U[k:, k]))) # fila del pivote: el mayor en valor absoluto
if p != k:
U[[k, p], k:] = U[[p, k], k:]
L[[k, p], :k] = L[[p, k], :k]
perm[[k, p]] = perm[[p, k]]
swaps += 1
if U[k, k] == 0.0: # columna nula desde la diagonal: no hay nada que eliminar
continue
m = U[k + 1:, k] / U[k, k] # multiplicadores
L[k + 1:, k] = m
U[k + 1:, k:] -= np.outer(m, U[k, k:])
return perm, L, np.triu(U), swaps
def det_lu(A):
_, _, U, s = lu_pivot(A)
return (-1) ** s * np.prod(np.diag(U))
def slogdet_lu(A):
"""(signo, log|det A|) sin formar el producto de los pivotes."""
_, _, U, s = lu_pivot(A)
d = np.diag(U)
if np.any(d == 0):
return 0.0, -np.inf
signo = (-1) ** s * np.prod(np.sign(d))
return float(signo), float(np.sum(np.log(np.abs(d))))
A = np.array([[0.0, 2.0, 1.0],
[1.0, 1.0, 0.0],
[3.0, 0.0, 4.0]])
perm, L, U, s = lu_pivot(A)
print("P A = L U:", np.allclose(A[perm], L @ U), " intercambios:", s)
print("pivotes:", np.diag(U))
print(f"det por LU: {det_lu(A):+.6f} NumPy: {np.linalg.det(A):+.6f}")
print("slogdet:", slogdet_lu(A), " NumPy:", np.linalg.slogdet(A))
B = rng.standard_normal((200, 200))
print(f"200×200: LU propia {slogdet_lu(B)[1]:.10f} NumPy {np.linalg.slogdet(B)[1]:.10f}")In the example pivoting makes two swaps, the pivots are , and , and . Now for overflow and underflow.
with np.errstate(over="ignore", under="ignore"):
for n in [100, 300, 400]:
print(f"n = {n}: det(0.1 I) = {np.linalg.det(0.1 * np.eye(n)):.3e} det(10 I) = {np.linalg.det(10 * np.eye(n)):.3e}")
print("slogdet(0.1 I_400):", np.linalg.slogdet(0.1 * np.eye(400)))
G = rng.standard_normal((500, 500))
print("\ndet de una gaussiana 500×500:", np.linalg.det(G))
s, l = slogdet_lu(G)
print(f"slogdet propio: signo {s:+.0f}, log|det| = {l:.4f} (|det| ≈ 10^{l / np.log(10):.1f})")
print("slogdet NumPy: ", np.linalg.slogdet(G))
piv = np.array([1e200, 1e200, 1e-200, 1e-200])
print("\nproducto directo de los pivotes:", np.prod(piv))
print("exp de la suma de logaritmos: ", np.exp(np.sum(np.log(piv))))The determinant of this Gaussian matrix is around : it does not fit in float64 and np.linalg.det returns , while its logarithm is a normal number. The last example is trickier: the determinant is exactly 1, but the product from left to right overflows at the second factor and never recovers.
The second lab checks that a linear map multiplies the area of any region, not just the square, by . A point lies in ellipse if and only if , and the box with the norm of row of contains it, because is that norm.
import matplotlib.pyplot as plt
A = np.array([[1.6, 0.9],
[-0.4, 1.1]])
area_teo = np.pi * abs(np.linalg.det(A))
h = np.linalg.norm(A, axis=1) # semianchos de la caja que contiene la elipse A·(disco)
caja = 4 * h[0] * h[1]
def estimar(N, rng):
Y = rng.uniform(-h, h, size=(N, 2)) # puntos uniformes en la caja
X = np.linalg.solve(A, Y.T) # sus preimágenes A⁻¹y
return caja * np.mean(np.sum(X**2, axis=0) <= 1) # y ∈ A·(disco) ⟺ ‖A⁻¹y‖ ≤ 1
Ns = np.array([100, 300, 1_000, 3_000, 10_000, 30_000])
rmse = []
for N in Ns:
est = np.array([estimar(N, rng) for _ in range(20)])
rmse.append(np.sqrt(np.mean((est - area_teo) ** 2)) / area_teo)
print(f"π|det A| = {area_teo:.5f} estimación con N = 200 000: {estimar(200_000, rng):.5f}")
fig, ax = plt.subplots(1, 2, figsize=(10, 4.2))
Y = rng.uniform(-h, h, size=(2500, 2))
dentro = np.sum(np.linalg.solve(A, Y.T) ** 2, axis=0) <= 1
ax[0].scatter(*Y[~dentro].T, s=4, color="0.75", label="fuera")
ax[0].scatter(*Y[dentro].T, s=4, label="dentro de A·(disco)")
t = np.linspace(0, 2 * np.pi, 300)
ax[0].plot(*(A @ np.vstack([np.cos(t), np.sin(t)])), color="k", lw=1.5)
ax[0].set_aspect("equal"); ax[0].legend(loc="upper right"); ax[0].set_title("2 500 puntos uniformes en la caja")
ax[1].loglog(Ns, rmse, "o-", label="error relativo (media de 20 repeticiones)")
ax[1].loglog(Ns, rmse[0] * np.sqrt(Ns[0] / Ns), "--", color="0.4", label="pendiente $-1/2$")
ax[1].set_xlabel("N"); ax[1].legend(); ax[1].set_title("El error cae como $1/\\sqrt{N}$")
plt.tight_layout(); plt.show()Monte Carlo error falls as , regardless of dimension; that makes it useful for high-dimensional volumes where grids are impossible. Finally, the cross product from its definition, checking its three geometric properties.
def cruz(u, v):
"""u × v desarrollando el determinante formal por su primera fila (e1, e2, e3)."""
return np.array([u[1] * v[2] - u[2] * v[1],
u[2] * v[0] - u[0] * v[2],
u[0] * v[1] - u[1] * v[0]])
u = np.array([2.0, 0.4, 0.0])
v = np.array([0.6, 1.6, 0.3])
w = np.array([0.4, 0.5, 1.5])
c = cruz(u, v)
print("u × v =", c, " (NumPy:", np.cross(u, v), ")")
print("ortogonal a u y a v:", u @ c, v @ c)
cos_t = u @ v / (np.linalg.norm(u) * np.linalg.norm(v))
print(f"‖u × v‖ = {np.linalg.norm(c):.6f} ‖u‖‖v‖ sen θ = {np.linalg.norm(u) * np.linalg.norm(v) * np.sqrt(1 - cos_t**2):.6f}")
print(f"w · (u × v) = {w @ c:.6f} det[u v w] = {np.linalg.det(np.column_stack([u, v, w])):.6f}")
print(f"det[u v (u × v)] = {np.linalg.det(np.column_stack([u, v, c])):.6f} = ‖u × v‖² = {c @ c:.6f}")
e1, e2, e3 = np.eye(3)
print("(e1 × e1) × e2 =", cruz(cruz(e1, e1), e2), " e1 × (e1 × e2) =", cruz(e1, cruz(e1, e2)))The professional version
np.linalg.det and np.linalg.slogdet do the same as your code: LU with partial pivoting (LAPACK’s getrf routine) and the product, or sum of logarithms, of pivots. SciPy exposes that factorization with scipy.linalg.lu_factor, which stores and in one matrix and the permutation as a vector piv of successive swaps: at step row was swapped with piv[i], so the number of swaps is the number of positions with piv[i] != i.
import scipy.linalg as sla
A = rng.standard_normal((6, 6))
lu, piv = sla.lu_factor(A) # L y U en una sola matriz; piv[i]: fila intercambiada con la i en el paso i
s = np.count_nonzero(piv != np.arange(6))
signo = (-1) ** s * np.prod(np.sign(np.diag(lu)))
logabs = np.sum(np.log(np.abs(np.diag(lu))))
print("desde lu_factor:", signo, logabs)
print("np.linalg.slogdet:", np.linalg.slogdet(A))
G = rng.standard_normal((300, 300))
t0 = time.perf_counter(); slogdet_lu(G); t1 = time.perf_counter(); np.linalg.slogdet(G); t2 = time.perf_counter()
print(f"300×300: LU propia {1e3 * (t1 - t0):.0f} ms, LAPACK {1e3 * (t2 - t1):.0f} ms")The typical application is high-dimensional Gaussian log-likelihood, as in a Gaussian process. The kernel matrix is symmetric positive definite, so Cholesky is used twice: for the log-determinant and to solve without inverting .
from scipy.stats import multivariate_normal
n = 200
x = np.linspace(0, 10, n)
K = np.exp(-0.5 * (x[:, None] - x[None, :]) ** 2 / 0.8**2) + 0.01 * np.eye(n) # kernel RBF + ruido
print("det K =", np.linalg.det(K)) # subdesbordamiento: 0.0
Lc = np.linalg.cholesky(K) # K = L Lᵀ
logdet = 2 * np.sum(np.log(np.diag(Lc))) # det K = (∏ L_ii)²
print(f"log det K por Cholesky: {logdet:.6f} slogdet: {np.linalg.slogdet(K)[1]:.6f}")
y = Lc @ rng.standard_normal(n) # una muestra de N(0, K)
alfa = sla.cho_solve((Lc, True), y) # K⁻¹ y sin invertir K
logp = -0.5 * y @ alfa - 0.5 * logdet - 0.5 * n * np.log(2 * np.pi)
print(f"log p(y) propio: {logp:.6f} SciPy: {multivariate_normal(np.zeros(n), K).logpdf(y):.6f}")With only 200 points, is around and rounds to 0, so np.log(np.linalg.det(K)) would give . Finally, Jacobi’s formula checked with finite differences: the gradient of is , even when the determinant is negative.
A = rng.standard_normal((4, 4))
eps = 1e-6
grad = np.zeros_like(A)
for i in range(4):
for j in range(4):
E = np.zeros_like(A); E[i, j] = eps
grad[i, j] = (np.linalg.slogdet(A + E)[1] - np.linalg.slogdet(A - E)[1]) / (2 * eps)
print("signo de det A:", np.linalg.slogdet(A)[0])
print("máx |gradiente numérico − A^{-T}|:", np.max(np.abs(grad - np.linalg.inv(A).T)))In PyTorch the equivalent is differentiable torch.linalg.slogdet, which produces exactly this gradient for a flow or Gaussian process trained with autograd:
import torch
A = torch.randn(512, 512, dtype=torch.float64, requires_grad=True)
sign, logabsdet = torch.linalg.slogdet(A) # LU con pivoteo, como LAPACK
logabsdet.backward() # A.grad == inv(A).T
K = A.detach() @ A.detach().T + torch.eye(512, dtype=torch.float64) # una matriz definida positiva
L = torch.linalg.cholesky(K)
logdet_K = 2 * torch.log(torch.diagonal(L)).sum() # igual que torch.logdet(K)
| Task | From scratch | Library |
|---|---|---|
| Determinant | det_lu: | np.linalg.det, torch.linalg.det |
| Signed log-determinant | slogdet_lu | np.linalg.slogdet, torch.linalg.slogdet |
| Factorization and sign | lu_pivot and its counter swaps | scipy.linalg.lu_factor and vector piv |
| Log-determinant of a positive definite matrix | np.linalg.cholesky, scipy.linalg.cho_factor | |
| Cross product | cruz | np.cross, torch.linalg.cross |
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
More than one answer may be correct.
slogdet_lu(A) returning (signo, logabsdet) with , using Gaussian elimination with partial pivoting. NumPy convention: if is singular, return (0.0, -inf). Do not use np.linalg.det or np.linalg.slogdet. Tests include matrices whose determinants overflow or underflow float64, so do not multiply the pivots and vectorize each update: three Python loops would take minutes for .import numpy as np
def slogdet_lu(A):
"""Devuelve (signo, log|det A|) a partir de PA = LU con pivoteo parcial."""
U = np.array(A, dtype=float)
n = U.shape[0]
signo, logabs = 1.0, 0.0
# tu código: elimina columna a columna eligiendo como pivote el mayor |U[i, k]| con i >= k,
# lleva la cuenta de los intercambios y acumula log|u_kk| en lugar de multiplicar los pivotes
return signo, logabsSummary
- Three axioms determine it: multilinear, alternating and . They yield Leibniz’s formula and uniqueness, and show that shears preserve it, dependent columns make it zero and a triangular determinant is the diagonal product.
- It is multiplicative: , because scales every region by the same factor. This gives , invariance under change of basis and, with , that is invertible if and only if .
- Compute it with LU, not the definition: in versus factorial cost for Leibniz or cofactors, and to avoid overflow; for positive definite matrices, using Cholesky.
- Cofactors, adjugate and Cramer provide formulas for reasoning and differentiation, not computation. They give , the gradient used by autograd.
- The Jacobian is its local version: scales volumes near , giving change of variables, transformed densities and normalizing-flow likelihood. In , the cross product and scalar triple product are the same determinant viewed as a normal vector and as volume.
- It does not measure closeness to singularity: mixes size and shape. Use and .