Construction of GHZ state

I’m thirsty for simulate n-qubie GHZ state in pennylane and I wanna ask how to simulate it in pennylane.

Hey @DonaldTrump! Welcome to the forum and love the enthusiasm :smiley:

I highly recommend that you check out some of our introductory content, of which we have many different offerings depending on how you like to learn :slight_smile::

To answer your question, though, there are a few ways you can prep a GHZ state in PennyLane:

  1. Gates: The GHZ state can be made with a Hadamard gate and a couple CNOTs

To do this in PennyLane, you just place the gates in a QNode and off you go!

import pennylane as qml

dev = qml.device("default.qubit")

@qml.qnode(dev)
def ghz():
    qml.Hadamard(0)
    qml.CNOT(wires=[0, 1])
    qml.CNOT(wires=[1, 2])

    return qml.state()

ghz()
tensor([0.70710678+0.j, 0.        +0.j, 0.        +0.j, 0.        +0.j,
        0.        +0.j, 0.        +0.j, 0.        +0.j, 0.70710678+0.j], requires_grad=True)
  1. “Direct” state prep: You can directly encode the state into the circuit like this:
import pennylane.numpy as np

@qml.qnode(dev)
def ghz():
    qml.StatePrep(np.array([1/np.sqrt(2), 0, 0, 0, 0, 0, 0, 1/np.sqrt(2)]), wires=range(3))
    return qml.state()

ghz()
tensor([0.70710678+0.j, 0.        +0.j, 0.        +0.j, 0.        +0.j,
        0.        +0.j, 0.        +0.j, 0.        +0.j, 0.70710678+0.j], requires_grad=True)

Anyway, if this is the start of your PennyLane journey, we’re glad to have you on board! Feel free to post any questions here that you may have along the way :grin:

@isaacdevlugt Please accept my heartfelt thanks!!You help me a lot!

1 Like

My pleasure! Glad I could help :slight_smile: