- Class reference.
- Complex number operations.
- Basic Design
- A complex number has two parts
- A real part (a) , a float
- An imaginary part (b) , a float
- a + bi
- $i = \sqrt{-1}$
- We probably want getters and setters for these
- constructor
- Real() -> real part
- Imag() -> returns imaginary part
- toString() -> returns string a+bi
- In addition, we will need a number of operations
- add
- subtract
- multiply
- divide
- distance from 0 or magnitude
- Classes in javascript
- No DEEP COPY
- No operator overload
- Only one constructor
- Private member data names begin with a #
- Members accessed via
this.member
- Basic syntax:
[export] class ClassName {
[optional field definitions]
constructor() {
}
Member1() {
}
...
}
- Let's start this class.
-
export class Complex {
#real
#imag
constructor (a=0, b=0) {
this.#real = a
this.#imag = b
}
toString() {
return this.#real + '+' + this.#imag + 'i'
}
}
- In main.js import this
import {complex} from "./complex.js"
- And test it
function TestComplex() {
let number = new Complex()
console.log(number.toString())
number = new Complex(1)
console.log(number.toString())
number = new Complex(3,2)
console.log(number.toString())
}
ChangePicture(inset, canvas);
TestComplex()
- Implement add
- And add to TestComplex()
let a = new Complex(3,4)
let b = new Complex(5,9)
let c = a.Add(b)
console.log(a.toString() , " + ", b.toString(), " = ", c.toString())
- Complex subtraction : a+bi - c+di = a-c + (b-d)i
- a+bi * c+di = ac-bd + (ad+cb)i
- $\frac{a+bi}{c+di} = \frac {ac + bd} {c^2 + d^2} + \frac{bc - ad}{c^2 + d^2}$
- Magnitude or distance from 0 for a number is
- $\sqrt{a^2 + b^2}$
- Note, you will need
Math.sqrt()
- implement and test this