-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tutorial Returning expectation values.py
69 lines (49 loc) · 1.75 KB
/
Tutorial Returning expectation values.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import json
import pennylane as qml
import pennylane.numpy as np
# Step 1: initialize a device
num_wires = 1
dev = qml.device("default.qubit", wires=num_wires)
# Step 2: Add a decorator below
@qml.qnode(dev)
def simple_circuit(angle):
"""
In this function:
* Rotate the qubit around the y-axis by angle
* Measure the expectation value of the Pauli X observable
Args:
angle (float): how much to rotate a state around the y-axis
Returns:
Union[tensor, float]: The expectation value of the Pauli X observable
"""
# Step 3: Add gates to the QNode
# Put your code here #
qml.RY(angle, wires=0)
# Step 4: Return the required expectation value
return qml.expval(qml.PauliX(0))
# These functions are responsible for testing the solution.
def run(test_case_input: str) -> str:
angle = json.loads(test_case_input)
output = simple_circuit(angle).numpy()
return str(output)
def check(solution_output: str, expected_output: str) -> None:
solution_output = json.loads(solution_output)
expected_output = json.loads(expected_output)
assert np.allclose(solution_output, expected_output, rtol=1e-4)
# These are the public test cases
test_cases = [
('1.23456', '0.9440031218347901'),
('2.957', '0.1835461227247332')
]
# This will run the public test cases locally
for i, (input_, expected_output) in enumerate(test_cases):
print(f"Running test case {i} with input '{input_}'...")
try:
output = run(input_)
except Exception as exc:
print(f"Runtime Error. {exc}")
else:
if message := check(output, expected_output):
print(f"Wrong Answer. Have: '{output}'. Want: '{expected_output}'.")
else:
print("Correct!")