1 | 'use strict'
|
2 |
|
3 | const Complex = require('../../type/complex/Complex')
|
4 | const typed = require('../../core/typed')
|
5 | const complex = Complex.factory(
|
6 | 'Complex', {}, '', typed, { on: function (x, y) {} }
|
7 | )
|
8 |
|
9 | function factory (type, config, load, typed) {
|
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 | const nthRoots = typed('nthRoots', {
|
43 | 'Complex': function (x) {
|
44 | return _nthComplexRoots(x, 2)
|
45 | },
|
46 | 'Complex, number': _nthComplexRoots
|
47 | })
|
48 | nthRoots.toTex = { 2: `\\{y : $y^{args[1]} = {\${args[0]}}\\}` }
|
49 | return nthRoots
|
50 | }
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 | const _calculateExactResult = [
|
59 | function realPos (val) { return complex(val) },
|
60 | function imagPos (val) { return complex(0, val) },
|
61 | function realNeg (val) { return complex(-val) },
|
62 | function imagNeg (val) { return complex(0, -val) }
|
63 | ]
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 | function _nthComplexRoots (a, root) {
|
72 | if (root < 0) throw new Error('Root must be greater than zero')
|
73 | if (root === 0) throw new Error('Root must be non-zero')
|
74 | if (root % 1 !== 0) throw new Error('Root must be an integer')
|
75 | if (a === 0 || a.abs() === 0) return [complex(0)]
|
76 | const aIsNumeric = typeof (a) === 'number'
|
77 | let offset
|
78 |
|
79 | if (aIsNumeric || a.re === 0 || a.im === 0) {
|
80 | if (aIsNumeric) {
|
81 | offset = 2 * (+(a < 0))
|
82 | } else if (a.im === 0) {
|
83 | offset = 2 * (+(a.re < 0))
|
84 | } else {
|
85 | offset = 2 * (+(a.im < 0)) + 1
|
86 | }
|
87 | }
|
88 | const arg = a.arg()
|
89 | const abs = a.abs()
|
90 | const roots = []
|
91 | const r = Math.pow(abs, 1 / root)
|
92 | for (let k = 0; k < root; k++) {
|
93 | const halfPiFactor = (offset + 4 * k) / root
|
94 | |
95 |
|
96 |
|
97 |
|
98 | if (halfPiFactor === Math.round(halfPiFactor)) {
|
99 | roots.push(_calculateExactResult[halfPiFactor % 4](r))
|
100 | continue
|
101 | }
|
102 | roots.push(complex({ r: r, phi: (arg + 2 * Math.PI * k) / root }))
|
103 | }
|
104 | return roots
|
105 | }
|
106 |
|
107 | exports.name = 'nthRoots'
|
108 | exports.factory = factory
|