-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcomplex.ts
More file actions
52 lines (42 loc) · 1.25 KB
/
complex.ts
File metadata and controls
52 lines (42 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// An arbitrary precision complex number library.
import { Fraction } from "./fraction.js"
export class Complex {
readonly real: Fraction
readonly imag: Fraction
constructor(real = new Fraction(0n, 1n), imag = new Fraction(0n, 1n)) {
this.real = real
this.imag = imag
}
plus(other: Complex) {
return new Complex(
this.real.plus(other.real),
this.imag.plus(other.imag),
)
}
minus(other: Complex) {
return new Complex(
this.real.minus(other.real),
this.imag.minus(other.imag),
)
}
times(other: Complex) {
return new Complex(
this.real.times(other.real).minus(this.imag.times(other.imag)),
this.imag.times(other.real).plus(this.real.times(other.imag)),
)
}
conj() {
return new Complex(this.real, this.imag.negate())
}
dividedBy(other: Complex) {
const partial = this.times(other.conj())
const bottom = other.real.square().plus(other.imag.square())
return new Complex(
partial.real.dividedBy(bottom),
partial.imag.dividedBy(bottom),
)
}
}
// (a + bi) / (c + di)
// (a+bi)(c-di) / (c+di)(c-di)
// (a+bi)(c-di) / (c^2+d^2)