Complex

import

import { Complex } from "@masabando/quantum-gates"

Description

The Complex class represents complex numbers and provides methods for complex number operations.

constructor

new Complex(realPart: number, imaginaryPart: number) : Complex

Creates a new complex number with the specified real (realPart) and imaginary (imaginaryPart) parts.

Methods

add

add(other: Complex) : Complex

Adds this complex number to another complex number (other) and returns the result as a new Complex instance.

Example

const a = new Complex(1, 2); // 1 + 2i
const b = new Complex(3, 4); // 3 + 4i
const result = a.add(b); // result is 4 + 6i

multiply

multiply(other: Complex) : Complex

Multiplies this complex number by another complex number (other) and returns the result as a new Complex instance.

Example

const a = new Complex(1, 2); // 1 + 2i
const b = new Complex(3, 4); // 3 + 4i
const result = a.multiply(b); // result is -5 + 10i

scale

scale(scalar: number) : Complex

Scales this complex number by a real number (scalar) and returns the result as a new Complex instance.

Example

const a = new Complex(1, 2); // 1 + 2i
const result = a.scale(3); // result is 3 + 6i

toString

toString(digits?: number) : string

Returns a string representation of the complex number. If digits is provided, the real and imaginary parts are formatted to the specified number of decimal places.

Example

const a = new Complex(1.23456, 2.34567);
console.log(a.toString()); // "1.23456 + 2.34567i"
console.log(a.toString(2)); // "1.23 + 2.35i"

magnitude

magnitude() : number

Returns the magnitude (absolute value) of the complex number.

Example

const a = new Complex(3, 4);
console.log(a.magnitude()); // 5

conjugate

conjugate() : Complex

Returns the complex conjugate of this complex number as a new Complex instance.

Example

const a = new Complex(1, 2); // 1 + 2i
const result = a.conjugate(); // result is 1 - 2i

Method Chaining

The methods of the Complex class can be chained together to perform multiple operations in a single expression.

Example

const a = new Complex(1, 2); // 1 + 2i
const b = new Complex(3, 4); // 3 + 4i
const result = a.add(b).scale(2).conjugate().toString(); // result is "-8 - 12i"
/* You can also break it down for clarity */
const anotherResult = a.add(b)
  .scale(2)
  .conjugate()
  .toString();