UNITARY_GROUP

Overview

The UNITARY_GROUP function generates random unitary matrices from the Haar distribution over the unitary group U(N). A unitary matrix is a complex square matrix U whose conjugate transpose equals its inverse, satisfying U^* U = U U^* = I. This property makes unitary matrices fundamental in quantum mechanics, signal processing, and numerical linear algebra.

The unitary group U(N) is the group of all N \times N unitary matrices under matrix multiplication. It forms a compact Lie group, which means it admits a unique probability measure that is invariant under group multiplication—this is the Haar measure. Sampling from the Haar measure produces matrices that are “uniformly random” over the group in a mathematically precise sense: any rotation of the sampled distribution yields the same distribution.

This implementation uses the scipy.stats.unitary_group module from SciPy. The algorithm follows the method described by Mezzadri (2007), which generates random matrices from classical compact groups efficiently. The approach involves:

  1. Generating a random complex matrix with entries drawn from independent standard complex normal distributions
  2. Applying QR decomposition to obtain an orthogonal factor
  3. Adjusting phases to ensure uniform distribution over U(N)

For reference, see F. Mezzadri, “How to generate random matrices from the classical compact groups”, Notices of the AMS, 54(5), 2007.

Unitary matrices sampled from the Haar distribution have applications in random matrix theory, quantum computing (where quantum gates are unitary operations), wireless communications (for channel modeling), and cryptography. The eigenvalues of Haar-distributed unitary matrices follow well-studied distributions connected to the Circular Unitary Ensemble (CUE) in random matrix theory.

This example function is provided as-is without any representation of accuracy.

Excel Usage

=UNITARY_GROUP(dim)
  • dim (int, required): Dimension of the unitary matrix to generate. Must be a positive integer.

Returns (list[list]): 2D list representing the unitary matrix. Elements are floats if purely real, or strings in the format “a+bj” for complex values. Returns an error message (str) if input is invalid.

Examples

Example 1: 2x2 unitary matrix

Inputs:

dim
2

Excel formula:

=UNITARY_GROUP(2)

Expected output:

"non-error"

Example 2: 3x3 unitary matrix

Inputs:

dim
3

Excel formula:

=UNITARY_GROUP(3)

Expected output:

"non-error"

Example 3: 4x4 unitary matrix

Inputs:

dim
4

Excel formula:

=UNITARY_GROUP(4)

Expected output:

"non-error"

Example 4: 5x5 unitary matrix

Inputs:

dim
5

Excel formula:

=UNITARY_GROUP(5)

Expected output:

"non-error"

Python Code

import numpy as np
from scipy.stats import unitary_group as scipy_unitary_group

def unitary_group(dim):
    """
    Generate a random unitary matrix of dimension N from the Haar distribution.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.unitary_group.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        dim (int): Dimension of the unitary matrix to generate. Must be a positive integer.

    Returns:
        list[list]: 2D list representing the unitary matrix. Elements are floats if purely real, or strings in the format "a+bj" for complex values. Returns an error message (str) if input is invalid.
    """
    EPSILON = 1e-12

    def to_int(x):
        """Convert to int, accepting floats that are whole numbers. Returns None if invalid."""
        if isinstance(x, bool):
            return None
        if isinstance(x, int):
            return x
        if isinstance(x, float) and x.is_integer():
            return int(x)
        return None

    def format_complex_value(value):
        """Format complex number for output."""
        real_part = float(value.real)
        imag_part = float(value.imag)
        if abs(imag_part) <= EPSILON:
            return real_part
        elif abs(real_part) <= EPSILON:
            return f"{imag_part}j"
        else:
            sign = "+" if imag_part >= 0 else "-"
            imag_value = abs(imag_part)
            return f"{real_part}{sign}{imag_value}j"

    # Validate input
    dim_int = to_int(dim)
    if dim_int is None or dim_int < 1:
        return "Invalid input: dim must be a positive integer."

    try:
        mat = scipy_unitary_group.rvs(dim_int)
    except Exception as e:
        return f"scipy.stats.unitary_group error: {e}"

    # Convert numpy array to 2D list with formatted complex numbers
    result = []
    for row in mat:
        output_row = []
        for value in row:
            if not np.isfinite(value.real) or not np.isfinite(value.imag):
                return "scipy.stats.unitary_group error: non-finite result encountered."
            output_row.append(format_complex_value(value))
        result.append(output_row)

    return result

Online Calculator