UNPKG

quaco.js

Version:

A lightweight modular Quantum Computing Simulator in JavaScript. Supports qubits, quantum gates, entanglement, circuits, algorithms, and visualization.

93 lines (83 loc) 2.31 kB
// src/utils/Complex.js /** * Class representing a complex number a + bi. */ export class Complex { constructor(re, im) { this.re = re; // Real part this.im = im; // Imaginary part } /** * Adds another complex number. * @param {Complex} other * @returns {Complex} */ add(other) { return new Complex(this.re + other.re, this.im + other.im); } /** * Subtracts another complex number. * @param {Complex} other * @returns {Complex} */ sub(other) { return new Complex(this.re - other.re, this.im - other.im); } /** * Multiplies with another complex number. * @param {Complex} other * @returns {Complex} */ mul(other) { return new Complex( this.re * other.re - this.im * other.im, this.re * other.im + this.im * other.re ); } /** * Divides by another complex number. * @param {Complex} other * @returns {Complex} */ div(other) { const denom = other.re * other.re + other.im * other.im; if (denom === 0) { throw new Error("Division by zero complex number"); } return new Complex( (this.re * other.re + this.im * other.im) / denom, (this.im * other.re - this.re * other.im) / denom ); } /** * Returns the magnitude (absolute value) of the complex number. * |z| = sqrt(re² + im²) * @returns {number} */ abs() { return Math.sqrt(this.re * this.re + this.im * this.im); } /** * Returns the squared magnitude |z|² = re² + im² * @returns {number} */ abs2() { return this.re * this.re + this.im * this.im; } /** * Returns the conjugate of the complex number. * @returns {Complex} */ conjugate() { return new Complex(this.re, -this.im); } /** * Returns a nicely formatted string for display. * @returns {string} */ toString() { const reStr = this.re.toFixed(4); const imStr = this.im >= 0 ? `+${this.im.toFixed(4)}i` : `${this.im.toFixed(4)}i`; return `${reStr}${imStr}`; } }