quaco.js
Version:
A lightweight modular Quantum Computing Simulator in JavaScript. Supports qubits, quantum gates, entanglement, circuits, algorithms, and visualization.
63 lines (57 loc) • 1.8 kB
JavaScript
// src/Qubit.js
import { Complex } from './utils/Complex.js';
import { MathUtils } from './utils/MathUtils.js';
/**
* Represents a single quantum bit (qubit).
* State is a 2-dimensional vector of complex numbers.
*/
export class Qubit {
constructor() {
// Start in |0> state
this.state = [
new Complex(1, 0), // α amplitude (for |0⟩)
new Complex(0, 0) // β amplitude (for |1⟩)
];
}
/**
* Applies a single qubit gate represented by a 2x2 matrix.
* @param {Complex[][]} gateMatrix 2x2 matrix of Complex numbers
*/
applyGate(gateMatrix) {
const newState = [
gateMatrix[0][0].mul(this.state[0]).add(gateMatrix[0][1].mul(this.state[1])),
gateMatrix[1][0].mul(this.state[0]).add(gateMatrix[1][1].mul(this.state[1]))
];
this.state = newState;
}
/**
* Measures the qubit, collapsing it to |0⟩ or |1⟩ based on probability.
* @returns {number} 0 or 1
*/
measure() {
const prob0 = this.state[0].abs2();
const rand = Math.random();
if (rand < prob0) {
// Collapse to |0>
this.state = [
new Complex(1, 0),
new Complex(0, 0)
];
return 0;
} else {
// Collapse to |1>
this.state = [
new Complex(0, 0),
new Complex(1, 0)
];
return 1;
}
}
/**
* Prints the current state of the qubit in Dirac notation.
*/
printState() {
const [alpha, beta] = this.state;
console.log(`|ψ⟩ = (${alpha.toString()})|0⟩ + (${beta.toString()})|1⟩`);
}
}