quantastica / quantum-circuit

Quantum Circuit Simulator implemented in JavaScript
MIT License
251 stars 50 forks source link

Hadamard Gate's probability #19

Closed icepolarizer closed 5 years ago

icepolarizer commented 5 years ago

I'm not sure I'm using this correctly, but I think there is some problem in hadamard gate. When I apply hadamard gate to every qubits and run them, they are mostly zero.

var qubitSystem = new QuantumCircuit(10);
qubitSystem.addGate("h", 1, [0,1,2,3,4,5,6,7,8,9]);
qubitSystem.run();
console.log(qubitSystem.measureAll());

This mostly returns zero-filled list. I know this is just a simulator, but I'm using this for my project, which includes some sort of Quantum Randint Generator. Could you please consider changing some probabilities of hadamard gate, when I measure them?

perak commented 5 years ago

Hi @kenixer

Problem is that you cannot add single-qubit gate to multiple wires in the same command, so you are not using it correctly.

Correct code would be:

var qubitSystem = new QuantumCircuit(10);
qubitSystem.addGate("h", -1, 0);
qubitSystem.addGate("h", -1, 1);
qubitSystem.addGate("h", -1, 2);
qubitSystem.addGate("h", -1, 3);
qubitSystem.addGate("h", -1, 4);
qubitSystem.addGate("h", -1, 5);
qubitSystem.addGate("h", -1, 6);
qubitSystem.addGate("h", -1, 7);
qubitSystem.addGate("h", -1, 8);
qubitSystem.addGate("h", -1, 9);
qubitSystem.run();
console.log(qubitSystem.measureAll());

(or even better - make a loop :) )

You can also try https://quantum-circuit.com - it uses this library and there is visual drag & drop editor.

perak commented 5 years ago

With loop:

var qubitSystem = new QuantumCircuit(10);

for(var i = 0; i < qubitSystem.numQubits; i++) {
    qubitSystem.addGate("h", -1, i);
}

qubitSystem.run();
console.log(qubitSystem.measureAll());
perak commented 5 years ago

-1 means "Add gate to the end of the wire".

You can also export circuit to svg picture and see what you've made (see docs).

perak commented 5 years ago

By the way, if you need random number generator, best way is to measure and store measurement into classical register, so you can directly access random integer without gymnastics, like this:

var quantumRandom = function() {
    var qubitSystem = new QuantumCircuit(10);

    for(var i = 0; i < qubitSystem.numQubits; i++) {
        // add Hadamard gate to i-th wire
        qubitSystem.addGate("h", -1, i);
        // add measurement gate to i-th qubit which will store result into classical register "C", into i-th classical bit
        qubitSystem.addMeasure(i, "c", i); 
    }

    qubitSystem.run();

    return qubitSystem.getCregValue("c");
};

// Usage
console.log(quantumRandom());
icepolarizer commented 5 years ago

Thanks. It helped me REALLY LOT. Thanks for making this great library. :1st_place_medal: