Skip to content

random.py

random_unitary

Sample a Haar-random unitary UU(n).

Constructs a complex Ginibre matrix Z and returns the Q factor of Z=QR with diagonal phase correction QQdiag(Rii/|Rii|).

py
def random_unitary(n: int) -> np.ndarray
Implementation
python
def random_unitary(n: int) -> np.ndarray:
    l: np.ndarray = N(size=(n, n)).astype(C128)
    r: np.ndarray = N(size=(n, n)).astype(C128)
    Q, R = LA.qr(l + 1j * r)
    A = np.diag([R[i, i] / np.abs(R[i, i]) for i in range(n)])
    return np.dot(Q, A)

random_state

Sample a Haar-random pure state |ψCn.

Draws a Haar unitary U and applies it to a uniformly chosen computational basis vector, then normalizes.

py
def random_state(n: int) -> np.ndarray
Implementation
python
def random_state(n: int) -> np.ndarray:
    U = random_unitary(n)
    vec = np.eye(n, dtype=C128)
    vec = vec[np.random.randint(0, n)]
    vec = np.dot(U, vec)
    vec /= LA.norm(vec)
    return vec.astype(C128)