complex.js

URL: https://mirkwood.cs.edinboro.edu/~bennett/class/cmsc3780/spring2026/notes/javascript/code/newton/complex.js
 
"use strict"

export class Complex{
    
    constructor(r,i) {
       this.real = r;
       this.imag = i;
    }

    Real() {
       return this.real;
    }

    Imag() {
        return this.imag;
    }

    toString() {
        return this.real + '+' + this.imag + 'i';
    }

    Add(other) {
       let rv = new Complex(this.real, this.imag);
       rv.real += other.real;
       rv.imag += other.imag;
       return (rv);
    }

    Sub(other) {
       let rv = new Complex(this.real,this.imag);
       rv.real -= other.real;
       rv.imag -= other.imag;
       return (rv);
    }

    Mult(other) {
       let rv = new Complex(0, 0);
       rv.real = this.real * other.real - this.imag * other.imag;
       rv.imag = this.real * other.imag + this.imag * other.real;
       return(rv);
    }

    Div(other) {
       let rv = new Complex(0, 0);
       let tmp = other.real * other.real + other.imag * other.imag;
       rv.real = (this.real * other.real + this.imag * other.imag)/tmp;
       rv.imag = (this.imag * other.real - this.real * other.imag)/tmp;
       return(rv);
    }

    Mag() {
       return Math.sqrt(this.real * this.real + this.imag * this.imag);
    }
}