qiskit/quantum_info/random/utils.py
def random_unitary(dim, seed=None):
    """
    Return a random dim x dim unitary Operator from the Haar measure.

    Args:
        dim (int): the dim of the state space.
        seed (int): Optional. To set a random seed.

    Returns:
        Operator: (dim, dim) unitary operator.

    Raises:
        QiskitError: if dim is not a positive power of 2.
    """
    if dim == 0 or not math.log2(dim).is_integer():
        raise QiskitError("Desired unitary dimension not a positive power of 2.")
    matrix = np.zeros([dim, dim], dtype=complex)
    for j in range(dim):
        if j == 0:
            a = random_state(dim, seed)
        else:
            a = random_state(dim)
        matrix[:, j] = np.copy(a)
        # Grahm-Schmidt Orthogonalize
        i = j-1
        while i >= 0:
            dc = np.vdot(matrix[:, i], a)
            matrix[:, j] = matrix[:, j]-dc*matrix[:, i]
            i = i - 1
        # normalize
        matrix[:, j] = matrix[:, j] * (1.0 / np.sqrt(np.vdot(matrix[:, j], matrix[:, j])))
    return Operator(matrix)
def random_unitary(dim, seed=None):
    if dim == 0 or not math.log2(dim).is_integer():
        raise QiskitError("Desired unitary dimension not a positive power of 2.")
    matrix = np.zeros([dim, dim], dtype=complex)
    for j in range(dim):
        if j == 0:
            a = random_state(dim, seed)
        else:
            a = random_state(dim)
        matrix[:, j] = np.copy(a)
        # Grahm-Schmidt Orthogonalize
        i = j-1
        while i >= 0:
            dc = np.vdot(matrix[:, i], a)
            matrix[:, j] = matrix[:, j]-dc*matrix[:, i]
            i = i - 1
        # normalize
        matrix[:, j] = matrix[:, j] * (1.0 / np.sqrt(np.vdot(matrix[:, j], matrix[:, j])))
    return Operator(matrix)
def random_unitary ( dim , seed = None ) : if dim == 0 or not math . log2 ( dim ) . is_integer ( ) : raise QiskitError ( "Desired unitary dimension not a positive power of 2." ) matrix = np . zeros ( [ dim , dim ] , dtype = complex ) for j in range ( dim ) : if j == 0 : a = random_state ( dim , seed ) else : a = random_state ( dim ) matrix [ : , j ] = np . copy ( a ) # Grahm-Schmidt Orthogonalize i = j - 1 while i >= 0 : dc = np . vdot ( matrix [ : , i ] , a ) matrix [ : , j ] = matrix [ : , j ] - dc * matrix [ : , i ] i = i - 1 # normalize matrix [ : , j ] = matrix [ : , j ] * ( 1.0 / np . sqrt ( np . vdot ( matrix [ : , j ] , matrix [ : , j ] ) ) ) return Operator ( matrix )
Return a random dim x dim unitary Operator from the Haar measure.

    Args:
        dim (int): the dim of the state space.
        seed (int): Optional. To set a random seed.

    Returns:
        Operator: (dim, dim) unitary operator.

    Raises:
        QiskitError: if dim is not a positive power of 2.
Return a random dim x dim unitary Operator from the Haar measure .