# qml.templates.subroutines.qmc.func_to_unitary¶

func_to_unitary(func, M)[source]

Calculates the unitary that encodes a function onto an ancilla qubit register.

Consider a function defined on the set of integers $$X = \{0, 1, \ldots, M - 1\}$$ whose output is bounded in the interval $$[0, 1]$$, i.e., $$f: X \rightarrow [0, 1]$$.

The func_to_unitary function returns a unitary $$\mathcal{R}$$ that performs the transformation:

$\mathcal{R} |i\rangle \otimes |0\rangle = |i\rangle\otimes \left(\sqrt{1 - f(i)}|0\rangle + \sqrt{f(i)} |1\rangle\right).$

In other words, for a given input state $$|i\rangle \otimes |0\rangle$$, this unitary encodes the amplitude $$\sqrt{f(i)}$$ onto the $$|1\rangle$$ state of the ancilla qubit. Hence, measuring the ancilla qubit will result in the $$|1\rangle$$ state with probability $$f(i)$$.

Parameters
• func (callable) – a function defined on the set of integers $$X = \{0, 1, \ldots, M - 1\}$$ with output value inside $$[0, 1]$$

• M (int) – the number of integers that the function is defined on

Returns

the $$\mathcal{R}$$ unitary

Return type

array

Raises

ValueError – if func is not bounded with $$[0, 1]$$ for all $$X$$

Example:

>>> func = lambda i: np.sin(i) ** 2
>>> M = 16
>>> func_to_unitary(func, M)
array([[ 1.        ,  0.        ,  0.        , ...,  0.        ,
0.        ,  0.        ],
[ 0.        , -1.        ,  0.        , ...,  0.        ,
0.        ,  0.        ],
[ 0.        ,  0.        ,  0.54030231, ...,  0.        ,
0.        ,  0.        ],
...,
[ 0.        ,  0.        ,  0.        , ..., -0.13673722,
0.        ,  0.        ],
[ 0.        ,  0.        ,  0.        , ...,  0.        ,
0.75968791,  0.65028784],
[ 0.        ,  0.        ,  0.        , ...,  0.        ,
0.65028784, -0.75968791]])