PennyLane
Previous

To attempt this challenge, please switch to a larger screen size.

Intermediate
Hamiltonians

Hamiltonians and Operator Arithmetic

Challenge statement

The Hamiltonian is the energy observable for a quantum system, and a quintessential component in many quantum algorithms. How do we implement Hamiltonians in PennyLane? You'll be tested on this in this challenge.

You will be tasked with creating the Hamiltonian

K = \frac{1}{3} \sum_{i < j} X_i X_j - \sum_{i = 0}^{n-1} Z_i,

where n is the number of qubits, X_i and Z_i are the familiar Pauli X and Z operators acting on the i-th wire, and \sum_{i < j} denotes a sum over all pairs (i,j) where i<j. For example, for n = 3, the pairs that enter the sum are (i,j) = (0, 1), (0, 2), (1, 2)). Note that we're indexing from 0!

In this challenge, you need to create the following quantum circuit simulation that returns the expectation value of this Hamiltonian.

Be mindful that the H gates represent the Hadamard gate, not the Hamiltonian, which we denoted by K to avoid this exact confusion!

Challenge code

In the code shown, you must complete two functions:

  • hamiltonian: responsible for creating the Hamiltonian in question for a general number of qubits (num_wires). You must complete this function.
  • expectation_value: simulates the circuit in question and returns the expectation value of the Hamiltonian in question. You must complete this function by creating a QNode within this function that returns the expectation value of the Hamiltonian.

Here are some helpful resources and hints:

  • The X_i X_j term, mathematically, denotes a tensor product between the two Pauli-X operators. Here are some ways you can perform this in PennyLane:
    • use the @ operator to take the tensor product between operators;
    • use qml.prod.
  • qml.Hamiltonian
  • Operator arithmetic

Input

As input to this problem, you are given the number of qubits num_wires (int), denoted by n in the above definition of the Hamiltonian K.

Output

This code must output the expectation value of the Hamiltonian (float).

Test cases

The following public test cases are available to you. Note that there are additional hidden test cases that we use to verify that your code is valid in full generality.

test_input: 8 expected_output: 9.33333 test_input: 3 expected_output: 1.00000

If your solution matches the correct one within the given tolerance specified in check (in this case it's a 1e-4 relative error tolerance), the output will be "Success!". Otherwise, you will receive an "Incorrect" prompt.

Good luck!

Loading...