qml.sample

sample(op=None, wires=None)[source]

Sample from the supplied observable, with the number of shots determined from the dev.shots attribute of the corresponding device. If no observable is provided then basis state samples are returned directly from the device.

The samples are drawn from the eigenvalues \(\{\lambda_i\}\) of the observable. The probability of drawing eigenvalue \(\lambda_i\) is given by \(p(\lambda_i) = |\langle \xi_i | \psi \rangle|^2\), where \(| \xi_i \rangle\) is the corresponding basis state from the observable’s eigenbasis.

Example

dev = qml.device("default.qubit", wires=2, shots=4)

@qml.qnode(dev)
def circuit(x):
    qml.RX(x, wires=0)
    qml.Hadamard(wires=1)
    qml.CNOT(wires=[0, 1])
    return qml.sample(qml.PauliY(0))

Executing this QNode:

>>> circuit(0.5)
array([ 1.,  1.,  1., -1.])

If no observable is provided, then the raw basis state samples obtained from device are returned (e.g., for a qubit device, samples from the computational device are returned). In this case, wires can be specified so that sample results only include measurement results of the qubits of interest.

dev = qml.device("default.qubit", wires=2, shots=4)

@qml.qnode(dev)
def circuit(x):
    qml.RX(x, wires=0)
    qml.Hadamard(wires=1)
    qml.CNOT(wires=[0, 1])
    return qml.sample()

Executing this QNode:

>>> circuit(0.5)
array([[0, 1],
       [0, 0],
       [1, 1],
       [0, 0]])
Parameters
  • op (Observable or None) – a quantum observable object

  • wires (Sequence[int] or int or None) – the wires we wish to sample from, ONLY set wires if op is None

Raises