Can someone help in this

def variance_experiment(n_shots):
“”"Run an experiment to determine the variance in an expectation
value computed with a given number of shots.

Args:
    n_shots (int): The number of shots
    
Returns:
    float: The variance in expectation value we obtain running the 
    circuit 100 times with n_shots shots each.
"""

# To obtain a variance, we run the circuit multiple times at each shot value.
n_trials = 100

##################
# YOUR CODE HERE #
##################

 # CREATE A DEVICE WITH GIVEN NUMBER OF SHOTS
dev = qml.device("default.qubit", wires=1, shots=n_shots)

@qml.qnode(dev)
# DECORATE THE CIRCUIT BELOW TO CREATE A QNODE

def circuit():
    qml.Hadamard(wires=0)
    return qml.expval(qml.PauliZ(wires=0))

# RUN THE QNODE N_TRIALS TIMES AND RETURN THE VARIANCE OF THE RESULTS
vals=[]
for _ in range(0,n_trials):
    vals.append(circuit())
    
return np.var(vals)

def variance_scaling(n_shots):
“”"Once you have determined how the variance in expectation value scales
with the number of shots, complete this function to programmatically
represent the relationship.

Args:
    n_shots (int): The number of shots
    
Returns:
    float: The variance in expectation value we expect to see when we run
    an experiment with n_shots shots.
"""

##################
# YOUR CODE HERE #
##################
dev = qml.device("default.qubit", wires=1, shots=n_shots)

@qml.qnode(dev)

# ESTIMATE THE VARIANCE BASED ON SHOT NUMBER
def circuit():
    qml.Hadamard(wires=0)
    return qml.expval(qml.PauliZ(0))
avals=[]
for _ in range(0,n_shots):
    avals.append(circuit())
return np.var(avals)

Various numbers of shots; you can change this

shot_vals = [10, 20, 40, 100, 200, 400, 1000, 2000, 4000]

Used to plot your results

results_experiment = [variance_experiment(shots) for shots in shot_vals]
results_scaling = [variance_scaling(shots) for shots in shot_vals]
plot = plotter(shot_vals, results_experiment, results_scaling)

Hi @Vedant_Dwivedi, it’s great that you’re trying out the codebook. What node is this?

code book exercise is I 10.4

Hi @Vedant_Dwivedi, you’re taking a complicated angle towards the second part of the question.

The easiest way to find the actual solution is to look at the graph in blue and think of what kind of function it is and how it relates to the number of shots. Are number of shots and variance directly proportional? Inversely proportional? Is this an exponential relation or a polynomial one?
Make a guess and see how it goes!

1 Like

Thanks :+1::v:@CatalinaAlbornoz