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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| function Complex(real, imag) { this.real = real this.imag = imag }
Complex.from = function (complexStr) { let real let imag if (complexStr.includes('+')) { let parts = complexStr.split('+') real = parseFloat(parts[0]) imag = parseFloat(parts[1]) } else { let parts = complexStr.split('-') if (parts.length == 2) { real = parseFloat(parts[0]) imag = -parseFloat(parts[1]) } else if (parts.length == 3) { real = -parseFloat(parts[1]) imag = -parseFloat(parts[2]) } } return new Complex(real, imag) }
Complex.isEqual = function (a, b) { return a.real == b.real && a.imag == b.imag }
Complex.prototype.plus = function (c) { var real = this.real + c.real var imag = this.imag + c.imag return new Complex(real, imag) } Complex.prototype.minus = function (c) { var real = this.real - c.real var imag = this.imag - c.imag return new Complex(real, imag) }
Complex.prototype.multiple = function (c) { var real = this.real * c.real - this.imag * c.imag var imag = this.real * c.imag + this.imag * c.real return new Complex(real, imag) } Complex.prototype.division = function (c) { var helper = new Complex(c.real, -c.imag) var m = helper.multiple(c) var z = helper.multiple(this) return new Complex(z.real / m.real, z.imag / m.real) }
Complex.prototype.division2 = function (c) { var a = c.real var b = -c.imag var m = a * a + b * b var real = this.real * a - this.imag * b var imag = this.real * b + this.imag * a return new Complex(real / m, imag / m) }
Complex.prototype.toString = function () { if (this.imag < 0) { return '(' + this.real + '' + this.imag + 'i)' } return '(' + this.real + '+' + this.imag + 'i)' }
|