Skip to content

← JAX Numerical Computing step 3 of 25

Medium Primitives

slogdet for Stable log|det|

Jump to the task

Keep a determinant's magnitude in log space

A determinant can be much larger or smaller than the entries of its matrix. For a diagonal matrix, it is the product of the diagonal entries. Multiplying many large magnitudes can overflow; multiplying many small magnitudes can underflow. The signs of the entries are a separate issue.

If you need the logarithm of the determinant's magnitude, use jnp.linalg.slogdet(A). It returns two scalars for a real square matrix:

  • sign: 1 for a positive determinant, -1 for a negative determinant, or 0 for a singular matrix.
  • logabsdet: the natural logarithm of the determinant's absolute value.

This avoids first forming a potentially unrepresentable determinant. Log-determinants appear in Gaussian log-likelihoods; log-absolute determinants also measure volume changes in invertible transformations.

Worked example

import jax.numpy as jnp

A = jnp.array([[-2.0, 0.0],
               [0.0, 3.0]])
sign, logabsdet = jnp.linalg.slogdet(A)
# sign: -1.0, because det(A) = -6
# logabsdet: approximately 1.791759, because log(abs(-6)) = log(6)

A negative determinant still has a valid real log-absolute value. Do not add log(sign): the real logarithm of -1 is NaN. If another calculation needs the sign, keep it as a separate value.

Why not take the logarithm afterward?

A float32 diagonal matrix with three entries of 1e20 has determinant about 1e60, beyond float32's finite range. Its log-absolute determinant is only about 138.1551. Forming the determinant first can produce infinity, and taking its logarithm afterward cannot recover the lost value. With three diagonal entries of 1e-20, the determinant is about 1e-60, while its log-absolute value is about -138.1551.

Matrix size alone does not determine the risk; entry magnitudes matter too. slogdet avoids the final product's range problem, but it does not eliminate all rounding errors or sensitivity in nearly singular matrices.

Problem

Implement log_abs_det(A) using jnp.linalg.slogdet and return only logabsdet.

  • A is a real square nonsingular float32 array of shape (n, n).
  • Return a scalar JAX floating-point value.
  • Positive and negative determinants are both allowed. The sign is not part of the returned result.

The identity matrix returns 0, because its determinant is 1. A determinant with magnitude below 1 gives a negative log-absolute value; that does not mean the determinant itself is negative.

Outside this exercise's nonsingular-input contract, a singular matrix yields sign 0 and log-absolute determinant negative infinity. A finite result is not a guarantee that the matrix is well-conditioned.