-
Notifications
You must be signed in to change notification settings - Fork 16
/
jmat_complex.js
1613 lines (1403 loc) · 60.7 KB
/
jmat_complex.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Jmat.js
Copyright (c) 2011-2020, Lode Vandevenne
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// REQUIRES: jmat_real.js
/*
Jmat.Complex: arithmetic on complex numbers
NOTE: treat Complex numbers as immutable unless you know nothing else refers to it. That is,
do not assign to .re and .im directly unless you created the instance yourself. Otherwise you
could be altering a global mathematical constant like pi, or a value that is shared by
different matrices, etc...
Overview of some functionality:
-elementary arithmetic: Complex.add, Complex.sub, Complex.mul, Complex.div
-mathematical functions: Complex.pow, Complex.exp, Complex.sqrt, Complex.log, Complex.cos, Complex.cosh, Complex.acos, ...
-special functions: Complex.erf, Complex.lambertw, Complex.gamma, Complex.loggamma (more are in jmat_special.js)
-fft
*/
/*
Constructor, but also usable without new as factory function.
Class representing a complex value with real and imaginary part.
Serves as both the actual object used as complex number, and namespace for most
complex mathematical functions.
The only sad thing is that Javascript doesn't support operator overloading
and nice expressions like a + b have to become a.add(b) instead
Infinity/NaN in re and/or im is used as follows (work in progress, this convention is not yet implemented by all functions and may change):
- (Infinity,Infinity) means: undirected infinity (idem if any is -Infinity)
- (Infinity,0), (0,Infinity), (-Infinity,0) and (0,-Infinity) are directed infinities in those 90 degree directions
- other directed angles are not yet implemented (TODO: use nonzero second number or a third extra variable in some way)
- infinities can mean either overflow or actual mathematical infinity, the distinction is not indicated.
- any NaN in either re or im means the entire complex value should be considered NaN
When used as factory function, makes it easy to construct values, e.g. if you
set C = Jmat.Complex, you can create real value 1 with C(1), or a complex value
with C('1+2i') or C(1, 2).
*/
Jmat.Complex = function(re, im) {
if(this instanceof Jmat.Complex) {
// Keyword "new" in front. Does not do any checks, to be "fast"
this.re = re;
this.im = im;
} else {
// No keyword "new" in front, use the convenience factory function instead
return Jmat.Complex.make(re, im); // This supports several argument types
}
};
// Create a new Jmat.Complex value. Copies Jmat.Complex if a Jmat.Complex is given as first argument
// with 0 arguments, creates zero value. With a and b numbers, creates complex number from it. With a Jmat.Complex object, copies it.
// the first parameter must be given and be number or Jmat.Complex. The second parameter is optional.
Jmat.Complex.make = function(a, b) {
if(a == undefined) return new Jmat.Complex(0, 0);
if(typeof a == 'number') return new Jmat.Complex(a, b == undefined ? 0 : b);
//if(a.raw && a.length == 1 && typeof a[0] == 'string' && a.raw[0] == a[0]) a = a[0]; // ES6: Complex`5+6i`
if(typeof a == 'string') return Jmat.Complex.parse(a);
return new Jmat.Complex(a.re, a.im); // Copy value object
};
// Create a new Jmat.Complex value, real
Jmat.Complex.newr = function(re) {
return new Jmat.Complex(re, 0);
};
// Create a new Jmat.Complex value, imaginary
Jmat.Complex.newi = function(im) {
return new Jmat.Complex(0, im);
};
// Create a new Jmat.Complex value, polar
Jmat.Complex.polar = function(r, a) {
return new Jmat.Complex(r * Math.cos(a), r * Math.sin(a));
};
// Create a new Jmat.Complex value, polar, angle in degrees
Jmat.Complex.polarDeg = function(r, a) {
a = Jmat.Real.degToRad(a);
return new Jmat.Complex(r * Math.cos(a), r * Math.sin(a));
};
// Casts the given number type to Jmat.Complex. If the given type is already of type Jmat.Complex, does not copy it but returns the input.
Jmat.Complex.cast = function(v) {
if(v && v.re != undefined) return v;
if(v == undefined) return Jmat.Complex(0);
return Jmat.Complex(v);
};
Jmat.Complex.castArray = function(a) {
var result = [];
for (var i = 0; i < a.length; i++) result[i] = Jmat.Complex.cast(a[i]);
return result;
};
//aka clone
Jmat.Complex.copy = function(v) {
return new Jmat.Complex(v.re, v.im);
};
// Because JS number toFixed appends zeros
Jmat.Complex.formatFloat_ = function(value, precision) {
var power = Math.pow(10, precision || 0);
return String(Math.round(value * power) / power);
};
//debugstring
Jmat.Complex.toString = function(value, opt_precision) {
if(!value) return value == 0 ? 'invalid0' : ('' + value);
var vre = value.re;
var vim = value.im;
if(!opt_precision && Math.abs(vre) < 1e-15 && Math.abs(vim) > 0.1) vre = 0; // avoid something hard to read like "2.220446049250313e-16+1i" due to numerical imprecision
if(!opt_precision && Math.abs(vim) < 1e-15 && Math.abs(vre) > 0.1) vim = 0; // avoid something hard to read like "2.220446049250313e-16+1i" due to numerical imprecision
var re = (opt_precision ? Jmat.Complex.formatFloat_(vre, opt_precision) : ('' + vre));
var im = (opt_precision ? Jmat.Complex.formatFloat_(vim, opt_precision) : ('' + vim));
if(im == '1') im = '';
if(im == '-1') im = '-';
if(vim == 0 || im == '0') return '' + re;
if(vre == 0) return '' + im + 'i';
if(vim < 0) return '' + re + im + 'i';
return '' + re + '+' + im + 'i';
};
Jmat.Complex.prototype.toString = function(opt_precision) {
return Jmat.Complex.toString(this, opt_precision);
};
Jmat.Complex.toStringPolar = function(value, opt_precision) {
if(!value) return value == 0 ? 'invalid0' : ('' + value);
var r = (opt_precision ? Jmat.Complex.formatFloat_(value.abs(), opt_precision) : ('' + value.abs()));
var a = (opt_precision ? Jmat.Complex.formatFloat_(value.arg(), opt_precision) : ('' + value.arg()));
return '' + r + '∠' + a;
};
Jmat.Complex.prototype.toStringPolar = function(opt_precision) {
return Jmat.Complex.toStringPolar(this, opt_precision);
};
// Test out this rendering: var c = Complex.polarDeg(1, 45); var d = Complex(1); for(var i = 0; i < 10; i++) { console.log(d.toStringPolarDeg() + ' ' + d.toString()); d = d.mul(c); }
Jmat.Complex.toStringPolarDeg = function(value, opt_precision) {
if(!value) return value == 0 ? 'invalid0' : ('' + value);
var arg = Jmat.Real.radToDeg(value.arg());
if(!opt_precision && Math.abs(arg - Math.round(arg)) < 1e-10) arg = Math.round(arg); // avoid something like "1∠89.99999999999999°" due to numerical imprecision
var r = (opt_precision ? Jmat.Complex.formatFloat_(value.abs(), opt_precision) : ('' + value.abs()));
var a = (opt_precision ? Jmat.Complex.formatFloat_(arg, opt_precision) : ('' + arg));
return '' + r + '∠' + a + '°';
};
Jmat.Complex.prototype.toStringPolarDeg = function(opt_precision) {
return Jmat.Complex.toStringPolarDeg(this, opt_precision);
};
// Parses strings of the form '5', '5+i', '5-2.3i', '1.25e-25+17.37e5i'
// Cannot (yet) parse the polar forms.
Jmat.Complex.parse = function(text) {
var i = text.indexOf('i');
if(i == -1) {
return Jmat.Complex(parseFloat(text));
} else {
if(text == 'i') return Jmat.Complex(0, 1);
text = text.substr(0, i); // remove the i and anything after it
text = text.replace(/ /g, ''); // support forms with spaces like '5 + 2i' too
// Make it handle it correctly if just 'i' without number in front is used
if(text[i - 1] == '+' || text[i - 1] == '-') text += '1';
// Find the + or - which is not after an 'e' or 'E'
for(var j = 1; j < text.length; j++) {
if((text[j] == '+' || text[j] == '-') && !(text[j - 1] == 'e' || text[j - 1] == 'E')) {
return Jmat.Complex(parseFloat(text.substr(0, j)), parseFloat(text.substr(j)));
}
}
return Jmat.Complex(0, parseFloat(text)); // pure imaginary
}
};
// Only use these as constants, never modify these, never return them!
Jmat.Complex.ZERO = Jmat.Complex(0);
Jmat.Complex.ONE = Jmat.Complex(1);
Jmat.Complex.TWO = Jmat.Complex(2);
Jmat.Complex.I = Jmat.Complex.newi(1);
Jmat.Complex.PI = Jmat.Complex(Math.PI);
Jmat.Complex.E = Jmat.Complex(Math.E);
Jmat.Complex.SQRT2 = Jmat.Complex(Math.sqrt(2));
Jmat.Complex.SQRTPI = Jmat.Complex(Math.sqrt(Math.PI));
Jmat.Complex.LOGPI = Jmat.Complex(Math.log(Math.PI));
Jmat.Complex.INVSQRT2PI = Jmat.Complex(Jmat.Real.INVSQRT2PI); //0.3989422804014327
Jmat.Complex.EM = Jmat.Complex(Jmat.Real.EM); // Euler-Mascheroni constant, aka Euler's gamma
Jmat.Complex.APERY = Jmat.Complex(Jmat.Real.APERY); // Apery's constant, zeta(3)
Jmat.Complex.real = function(z) {
return Jmat.Complex(z.re);
};
Jmat.Complex.prototype.real = function() {
return Jmat.Complex(this.re);
};
Jmat.Complex.imag = function(z) {
return Jmat.Complex(z.im);
};
Jmat.Complex.prototype.imag = function() {
return Jmat.Complex(this.im);
};
//Basic operators
Jmat.Complex.add = function(x, y) {
return new Jmat.Complex(x.re + y.re, x.im + y.im);
};
Jmat.Complex.prototype.add = function(y) {
return new Jmat.Complex(this.re + y.re, this.im + y.im);
};
Jmat.Complex.sub = function(x, y) {
return new Jmat.Complex(x.re - y.re, x.im - y.im);
};
Jmat.Complex.prototype.sub = function(y) {
return new Jmat.Complex(this.re - y.re, this.im - y.im);
};
Jmat.Complex.mul = function(x, y) {
if(x.im == 0 && y.im == 0) {
return new Jmat.Complex(x.re * y.re, 0);
}
if(Jmat.Complex.isInfOrNaN(x) || Jmat.Complex.isInfOrNaN(y)) {
if(Jmat.Complex.isNaN(x) || Jmat.Complex.isNaN(y)) {
return new Jmat.Complex(NaN, NaN);
}
if((Jmat.Real.isInf(x.re) && Jmat.Real.isInf(x.im)) ||
Jmat.Real.isInf(y.re) && Jmat.Real.isInf(y.im)) {
// undirected infinity
return new Jmat.Complex(Infinity, Infinity);
}
// TODO: also support the directed infinities
}
var re = x.re * y.re - x.im * y.im;
var im = x.im * y.re + x.re * y.im;
return new Jmat.Complex(re, im);
};
Jmat.Complex.prototype.mul = function(y) {
return Jmat.Complex.mul(this, y);
};
Jmat.Complex.div = function(x, y) {
if(x.im == 0 && y.im == 0) {
return new Jmat.Complex(x.re / y.re, 0);
} else {
if(Jmat.Complex.isInf(x) && !Jmat.Complex.isInfOrNaN(y)) {
// Result should be some infinity (because it's infinity divided through finite value), but the formula below would give a NaN somewhere.
// 4 possible rotations of the infinity, based on quadrant of y (TODO: THIS IS IGNORED NOW!!)
return x;
}
var d = y.re * y.re + y.im * y.im;
if(d == Infinity || d == -Infinity) {
// the calculations below would give Infinity/Infinity = NaN even though result should be 0.
if(!Jmat.Complex.isInfOrNaN(x)) return Jmat.Complex(0);
}
if(d == 0 && !Jmat.Complex.isInfOrNaN(x) && (x.re != 0 || x.im != 0)) {
// the calculations below would give 0/0 = NaN even though result should be some infinity.
return new Jmat.Complex(x.re == 0 ? 0 : (x.re < 0 ? -Infinity : Infinity), x.im == 0 ? 0 : (x.im < 0 ? -Infinity : Infinity));
}
d = 1.0 / d; // optimization: avoid multiple times the same division
var re, im;
if(d > 1) {
re = (x.re * y.re + x.im * y.im) * d;
im = (x.im * y.re - x.re * y.im) * d;
} else {
// the multiplications with d are in the center, to avoid overflow in case e.g. x.re*y.re overflows floating point
re = x.re * d * y.re + x.im * d * y.im;
im = x.im * d * y.re - x.re * d * y.im;
}
return new Jmat.Complex(re, im);
}
};
Jmat.Complex.prototype.div = function(y) {
return Jmat.Complex.div(this, y);
};
Jmat.Complex.addr = function(z, a) {
return new Jmat.Complex(z.re + a, z.im);
};
Jmat.Complex.prototype.addr = function(a) {
return new Jmat.Complex(this.re + a, this.im);
};
Jmat.Complex.addi = function(z, a) {
return new Jmat.Complex(z.re, z.im + a);
};
Jmat.Complex.prototype.addi = function(a) {
return new Jmat.Complex(this.re, this.im + a);
};
Jmat.Complex.subr = function(z, a) {
return new Jmat.Complex(z.re - a, z.im);
};
Jmat.Complex.prototype.subr = function(a) {
return new Jmat.Complex(this.re - a, this.im);
};
// Subtract z from real.
Jmat.Complex.rsub = function(a, z) {
return new Jmat.Complex(a - z.re, -z.im);
};
// Subtract self from real. This operator exists because it's less awkward to write z.rsub(3) than Complex(3).sub(z) in long formulas
Jmat.Complex.prototype.rsub = function(a) {
return new Jmat.Complex(a - this.re, -this.im);
};
Jmat.Complex.subi = function(z, a) {
return new Jmat.Complex(z.re, z.im - a);
};
Jmat.Complex.prototype.subi = function(a) {
return new Jmat.Complex(this.re, this.im - a);
};
Jmat.Complex.mulr = function(z, a) {
return new Jmat.Complex(z.re * a, z.im * a);
};
Jmat.Complex.prototype.mulr = function(a) {
return new Jmat.Complex(this.re * a, this.im * a);
};
// multiply with imaginary number given as real
Jmat.Complex.muli = function(z, a) {
return new Jmat.Complex(-z.im * a, z.re * a);
};
Jmat.Complex.prototype.muli = function(a) {
return new Jmat.Complex(-this.im * a, this.re * a);
};
Jmat.Complex.divr = function(z, a) {
return new Jmat.Complex(z.re / a, z.im / a);
};
Jmat.Complex.prototype.divr = function(a) {
return new Jmat.Complex(this.re / a, this.im / a);
};
// Divide real a through z.
Jmat.Complex.rdiv = function(a, z) {
return new Jmat.Complex.div(Jmat.Complex(a), z);
};
// Divide real a through self. This operator exists because it's less awkward to write z.rsub(3) than Complex(3).div(z) in long formulas
Jmat.Complex.prototype.rdiv = function(a) {
return Jmat.Complex.div(Jmat.Complex(a), this);
};
// divide through imaginary number given as real
Jmat.Complex.divi = function(z, a) {
return new Jmat.Complex(z.im / a, -z.re / a);
};
Jmat.Complex.prototype.divi = function(a) {
return new Jmat.Complex(this.im / a, -this.re / a);
};
//rotate complex number z by a radians. That is, change its argument. a is real (JS number).
Jmat.Complex.rotate = function(z, a) {
if(a == 0) return z;
return Jmat.Complex.polar(z.abs(), z.arg() + a);
};
//rotate complex number z by 2pi/n radians. This results in giving the next solution of the nth root.
Jmat.Complex.nextroot = function(z, n) {
var result = Jmat.Complex.rotate(z, Math.PI * 2 / n);
if(Jmat.Real.near(result.im, 0, 1e-14)) result.im = 0;
return result;
};
// mod operation, result has the sign of the divisor (unlike % operator in JS, Java and C99), so it's like wrapping x in range 0..y.
// works on real or complex numbers too, e.g. (6+4i) mod (3+5i) gives (-2+2i)
Jmat.Complex.mod = function(x, y) {
if(x.im != 0 || y.im != 0) return x.sub(Jmat.Complex.floor(x.div(y)).mul(y));
return Jmat.Complex(Jmat.Real.mod(x.re, y.re));
};
// remainder operation, like the % operator in JS, Java and C99.
Jmat.Complex.rem = function(x, y) {
if(x.im != 0 || y.im != 0) return x.sub(Jmat.Complex.trunc(x.div(y)).mul(y));
return Jmat.Complex(x.re % y.re);
};
Jmat.Complex.wrap = function(x, from, to) {
return new Jmat.Complex(Jmat.Real.wrap(x.re, from.re, to.re), Jmat.Real.wrap(x.im, from.im, to.im));
};
Jmat.Complex.clamp = function(x, from, to) {
return new Jmat.Complex(Jmat.Real.clamp(x.re, from.re, to.re), Jmat.Real.clamp(x.im, from.im, to.im));
};
//Like JS ~: returns -(x + 1), limited to 32-bit int
Jmat.Complex.bitneg = function(x) {
var result = Jmat.Complex(0);
result.re = ~x.re;
//imaginary part not bit-negated on purpose: otherwise it appears when bit-inverting real number, which is in 99.9% of the cases not wanted
//instead negated, to follow the formula -(x + 1)
//result.im = ~x.im;
result.im = -x.im;
return result;
};
Jmat.Complex.bitand = function(x, y) {
var result = Jmat.Complex(0);
result.re = x.re & y.re;
result.im = x.im & y.im;
return result;
};
Jmat.Complex.bitor = function(x, y) {
var result = Jmat.Complex(0);
result.re = x.re | y.re;
result.im = x.im | y.im;
return result;
};
Jmat.Complex.bitxor = function(x, y) {
var result = Jmat.Complex(0);
result.re = x.re ^ y.re;
result.im = x.im ^ y.im;
return result;
};
Jmat.Complex.lshift = function(x, y) {
var result = Jmat.Complex(0);
result.re = x.re << y.re;
result.im = x.im << y.im;
return result;
};
Jmat.Complex.rshift = function(x, y) {
var result = Jmat.Complex(0);
result.re = x.re >> y.re;
result.im = x.im >> y.im;
return result;
};
Jmat.Complex.neg = function(x) {
return Jmat.Complex(-x.re, -x.im);
};
Jmat.Complex.prototype.neg = function() {
return Jmat.Complex(-this.re, -this.im);
};
// Returns 0 if z is 0, 1 if z is positive, -1 if z is negative. For complex z, returns z / abs(z)
// Another name for this could be "normalize" as it makes the length of the "vector" 1
Jmat.Complex.sign = function(z) {
if (z.im == 0) {
if(z.re == 0) return Jmat.Complex(0);
else if(z.re < 0) return Jmat.Complex(-1);
return Jmat.Complex(1);
}
return z.divr(z.abs());
};
// Returns 0 if z is 0, 1 if z is positive, -1 if z is negative. For complex z, returns sign of z.im if z.re == 0, sign of z.re otherwise (that is, the function returns sqrt(z*z) / z, except for z=0)
Jmat.Complex.csgn = function(z) {
if (Jmat.Real.near(z.re, 0, 1e-15)) { //avoid numeric imprecisions for e.g. the values of e.g. acosh
if(z.im == 0) return Jmat.Complex(0);
else if(z.im < 0) return Jmat.Complex(-1);
return Jmat.Complex(1);
} else {
if(z.re == 0) return Jmat.Complex(0);
else if(z.re < 0) return Jmat.Complex(-1);
return Jmat.Complex(1);
}
};
// Similar to sign, but returns 1 if the input is 0
Jmat.Complex.sign1 = function(z) {
if (z.im == 0) {
if(z.re < 0) return Jmat.Complex(-1);
return Jmat.Complex(1);
}
return z.divr(z.abs());
};
// Similar to csgn, but returns 1 if the input is 0
Jmat.Complex.csgn1 = function(z) {
if (Jmat.Real.near(z.re, 0, 1e-15)) { //avoid numeric imprecisions
if(z.im < 0) return Jmat.Complex(-1);
return Jmat.Complex(1);
} else {
if(z.re < 0) return Jmat.Complex(-1);
Jmat.Complex(1);
}
};
// applies sign of y to x, so the result has the magnitude of x but the argument of y
Jmat.Complex.copysign = function(x, y) {
return Jmat.Complex.abs(x).mul(Jmat.Complex.sign(y));
};
Jmat.Complex.conj = function(x) {
return Jmat.Complex(x.re, -x.im);
};
Jmat.Complex.prototype.conj = function() {
return Jmat.Complex(this.re, -this.im);
};
Jmat.Complex.eq = function(x, y) {
if(!x || !y) return x == y;
return (x.re == y.re && x.im == y.im);
};
Jmat.Complex.prototype.eq = function(y) {
return y && this.re == y.re && this.im == y.im;
};
Jmat.Complex.eqr = function(x, y) {
return (x.re == y && x.im == 0);
};
Jmat.Complex.prototype.eqr = function(y) {
return (this.re == y && this.im == 0);
};
Jmat.Complex.inv = function(z) {
return Jmat.Complex.ONE.div(z);
};
Jmat.Complex.prototype.inv = function() {
return Jmat.Complex.ONE.div(this);
};
//increment
Jmat.Complex.inc = function(z) {
return new Jmat.Complex(z.re + 1, z.im);
};
Jmat.Complex.prototype.inc = function() {
return new Jmat.Complex(this.re + 1, this.im);
};
//decrement
Jmat.Complex.dec = function(z) {
return new Jmat.Complex(z.re - 1, z.im);
};
Jmat.Complex.prototype.dec = function() {
return new Jmat.Complex(this.re - 1, this.im);
};
// TODO: consider no longer have prototype.abs return real and Complex.abs return Complex. Use absr for real instead (or absc for complex).
// absolute value, aka modulus of complex number, as a Jmat.Complex object (its imaginary part is 0)
Jmat.Complex.abs = function(x) {
return Jmat.Complex(x.abs());
};
// absolute value, aka modulus of complex number, returned as real (regular JS number, to be similar to .re and .im)
Jmat.Complex.prototype.abs = function() {
if(this.im == 0) return Math.abs(this.re);
if(this.re == 0) return Math.abs(this.im);
if(this.re == Infinity || this.re == -Infinity || this.im == Infinity || this.im == -Infinity) {
return Infinity;
}
// Numerically more stable version of "Math.sqrt(x.re * x.re + x.im * x.im);"
return Jmat.Real.hypot(this.re, this.im);
};
// absolute value squared, returned as Jmat.Complex object. This is faster than abs due to not taking sqrt.
Jmat.Complex.abssq = function(x) {
return Jmat.Complex(x.re * x.re + x.im * x.im);
};
// absolute value squared, returned as real (regular JS number). This is faster than abs due to not taking sqrt.
Jmat.Complex.prototype.abssq = function() {
return this.re * this.re + this.im * this.im;
};
// returns the complex argument in range -PI to +PI, as a Jmat.Complex object (its imaginary part is 0)
Jmat.Complex.arg = function(x) {
return Jmat.Complex(x.arg());
};
// returns the complex argument in range -PI to +PI, as a real (regular JS number, to be similar to .re and .im)
Jmat.Complex.prototype.arg = function() {
if(this.im == 0) return this.re < 0 ? Math.PI : 0;
return Math.atan2(this.im, this.re);
};
//returns result in range 0-1 rather than -PI to PI, as a regular JS number. Useful for graphical representations, not for math. 0 matches 0 degrees, 0.5 matches 180 degrees, 0.999 matches around 359 degrees.
Jmat.Complex.arg1 = function(z) {
var result = z.arg();
if(result < 0) result += 2 * Math.PI;
result /= (2 * Math.PI);
if(result < 0) result = 0;
if(result > 1) result = 1;
return result;
};
//manhattan norm, returned as real
Jmat.Complex.abs1r = function(x) {
return Math.abs(x.re) + Math.abs(x.im);
};
// returns sqrt(|x|^2 + |y|^2) with numerically more precise formula ; a companion to atan2
// if more than 2 arguments are given, calculates norm of all arguments
Jmat.Complex.hypot = function(x, y) {
var C = Jmat.Complex;
if(C.abs1r(y) > C.abs1r(x)) {
var temp = x;
x = y;
y = temp;
}
if(C.isInf(x)) return Infinity;
var t = y.div(x);
return x.mul(C.sqrt(C.abssq(t).addr(1)));
};
////////////////////////////////////////////////////////////////////////////////
// Categories
////////////////////////////////////////////////////////////////////////////////
Jmat.Complex.isReal = function(z) {
return z.im == 0;
};
Jmat.Complex.isImaginary = function(z) {
return z.re == 0;
};
Jmat.Complex.isInt = function(z) {
return z.im == 0 && Jmat.Real.isInt(z.re);
};
// Gaussian integer
Jmat.Complex.isGaussian = function(z) {
return Jmat.Real.isInt(z.re) && Jmat.Real.isInt(z.im);
};
Jmat.Complex.isNaN = function(z) {
return !z || isNaN(z.re) || isNaN(z.im);
};
//is infinite
Jmat.Complex.isInf = function(z) {
return z.re == Infinity || z.re == -Infinity || z.im == Infinity || z.im == -Infinity;
};
//isnanorinf isinfornan
Jmat.Complex.isInfOrNaN = function(z) {
return Jmat.Complex.isNaN(z) || Jmat.Complex.isInf(z);
};
//real and strictly positive
Jmat.Complex.isPositive = function(z) {
return z.re > 0 && z.im == 0;
};
//real and strictly negative
Jmat.Complex.isNegative = function(z) {
return z.re < 0 && z.im == 0;
};
Jmat.Complex.isPositiveOrZero = function(z) {
return z.re >= 0 && z.im == 0;
};
Jmat.Complex.isNegativeOrZero = function(z) {
return z.re <= 0 && z.im == 0;
};
//strictly positive
Jmat.Complex.isPositiveInt = function(z) {
return Jmat.Complex.isInt(z) && z.re > 0;
};
//strictly negative
Jmat.Complex.isNegativeInt = function(z) {
return Jmat.Complex.isInt(z) && z.re < 0;
};
Jmat.Complex.isPositiveIntOrZero = function(z) {
return Jmat.Complex.isInt(z) && z.re >= 0;
};
Jmat.Complex.isNegativeIntOrZero = function(z) {
return Jmat.Complex.isInt(z) && z.re <= 0;
};
// z is odd integer
Jmat.Complex.isOdd = function(z) {
return Jmat.Complex.isInt(z) && Math.abs(z.re % 2) == 1;
};
// z is even integer
Jmat.Complex.isEven = function(z) {
return Jmat.Complex.isInt(z) && z.re % 2 == 0;
};
////////////////////////////////////////////////////////////////////////////////
Jmat.Complex.pow = function(x, y) {
var C = Jmat.Complex;
if(C.isReal(x) && C.isReal(y) && (x.re >= 0 || y.re == Infinity || y.re == -Infinity || Jmat.Real.isInt(y.re))) {
//if(x.re == 0 && y.re == 0) return C(NaN); // JS's pow returns 1 for 0^0
// It is chosen to return 1 for 0^0, not NaN. NaN is mathematically more correct, however 0^0 is correct in many practical applications.
return C(Math.pow(x.re, y.re));
} else if(x.eqr(0)) {
return y.re == 0 ? C(NaN) : C(y.re < 0 ? Infinity : 0);
} else {
// This is just one branch. In fact it returns a complex result for -3 ^ (1/3),
// the cube root of -3. To get the real result, use absolute value (and then negate) on it.
// This is correct: the principal result of the cube root for this is a complex number.
// Note: This returns incorrect values for a negative real to the power of Infinity: the result should be -Infinity for < -1, 0 for > -1, NaN for -1, but it always gives NaN. However, the "if" part above already handles that.
var r = x.abs();
var t = x.arg();
var u = Math.pow(r, y.re) * Math.exp(-y.im * t);
if(isNaN(u)) {
u = Math.pow(1, y.re / r) * Math.exp(-y.im * t / r);
if(u < 0) u = -Infinity;
else if(u > 0) u = Infinity;
else u = NaN;
}
var v = y.im * Math.log(r) + y.re * t;
return C(u * Math.cos(v), u * Math.sin(v));
}
};
Jmat.Complex.prototype.pow = function(y) {
return Jmat.Complex.pow(this, y);
};
Jmat.Complex.powr = function(z, a) {
return Jmat.Complex.pow(z, Jmat.Complex(a));
};
Jmat.Complex.prototype.powr = function(a) {
return Jmat.Complex.pow(this, Jmat.Complex(a));
};
// raise regular js number x, to complex power a
Jmat.Complex.rpow = function(x, a) {
return Jmat.Complex.pow(Jmat.Complex(x), a);
};
// raise regular js number x, to this complex number
Jmat.Complex.prototype.rpow = function(x) {
return Jmat.Complex.pow(Jmat.Complex(x), this);
};
Jmat.Complex.sin = function(z) {
if(z.im == 0) return Jmat.Complex(Math.sin(z.re));
var iz = Jmat.Complex(-z.im, z.re);
var eiz = Jmat.Complex.exp(iz);
var ieiz = Jmat.Complex.inv(eiz);
return eiz.sub(ieiz).div(Jmat.Complex(0, 2));
};
//unnormalized sinc: sin(x) / x, but also defined for x = 0
Jmat.Complex.sinc = function(z) {
if(z.eqr(0)) return Jmat.Complex(1);
return Jmat.Complex.sin(z).div(z);
};
Jmat.Complex.cos = function(z) {
if(z.im == 0) return Jmat.Complex(Math.cos(z.re));
var iz = Jmat.Complex(-z.im, z.re);
var eiz = Jmat.Complex.exp(iz);
var ieiz = Jmat.Complex.inv(eiz);
return eiz.add(ieiz).mulr(0.5);
};
Jmat.Complex.tan = function(z) {
if(z.im == 0) return Jmat.Complex(Math.tan(z.re));
var iz = Jmat.Complex(-z.im, z.re);
var eiz = Jmat.Complex.exp(iz);
var ieiz = Jmat.Complex.inv(eiz);
return (eiz.sub(ieiz).div(Jmat.Complex(0, 2))).div(eiz.add(ieiz).mulr(0.5)); // Jmat.Complex.sin(z).div(Jmat.Complex.cos(z));
};
Jmat.Complex.asin = function(z) {
if(z.im == 0 && z.re >= -1 && z.re <= 1) return Jmat.Complex(Math.asin(z.re));
var s = Jmat.Complex.sqrt(Jmat.Complex.ONE.sub(z.mul(z)));
var l = Jmat.Complex.log(Jmat.Complex(-z.im, z.re).add(s));
return Jmat.Complex(l.im, -l.re);
};
Jmat.Complex.acos = function(z) {
if(z.im == 0 && z.re >= -1 && z.re <= 1) return Jmat.Complex(Math.acos(z.re));
//i * ln(x - i * sqrt(1-x^2))
var s = Jmat.Complex.sqrt(Jmat.Complex.ONE.sub(z.mul(z))).mul(Jmat.Complex.I);
var l = Jmat.Complex.log(z.add(s));
return Jmat.Complex(l.im, -l.re);
};
Jmat.Complex.atan = function(z) {
if(z.im == 0) return Jmat.Complex(Math.atan(z.re));
var iz = Jmat.Complex(-z.im, z.re);
var b = Jmat.Complex.ONE.sub(iz).div(iz.inc());
var l = Jmat.Complex.log(b);
return Jmat.Complex(-0.5 * l.im, 0.5 * l.re);
};
Jmat.Complex.atan2 = function(y, x) {
var C = Jmat.Complex;
if(!C.isReal(x) || !C.isReal(y)) {
// The simple definition atan(y / x) is incorrect for most of the domain
// Better definition: -i*log((x+i*y) / sqrt(x^2+y^2))
if(x.re < 0 && y.eqr(0)) return C(Math.PI / 2);
return C.log(x.add(y.mul(C.I)).div(C.sqrt(x.mul(x).add(y.mul(y))))).mul(C.I).neg();
} else {
var result = C(0);
result.re = Math.atan2(y.re, x.re);
return result;
}
};
Jmat.Complex.sinh = function(z) {
var e = Jmat.Complex.exp(z);
var ei = Jmat.Complex.inv(e);
return e.sub(ei).divr(2);
};
Jmat.Complex.cosh = function(z) {
var e = Jmat.Complex.exp(z);
var ei = Jmat.Complex.inv(e);
return e.add(ei).divr(2);
};
Jmat.Complex.tanh = function(z) {
// at z.re > 709, exp gives infinity, at z.re > 304, it gets wrong value if z.im != 0
if(z.re > 350) return Jmat.Complex(1);
if(z.re < -350) return Jmat.Complex(-1);
var e = Jmat.Complex.exp(z);
var ei = Jmat.Complex.inv(e);
return e.sub(ei).div(e.add(ei));
};
Jmat.Complex.asinh = function(z) {
return Jmat.Complex.log(z.add(Jmat.Complex.sqrt(z.mul(z).addr(1))));
};
Jmat.Complex.acosh = function(z) {
// ln(x + sqrt(z-1)*sqrt(z+1))
return Jmat.Complex.log(z.add(Jmat.Complex.sqrt(z.subr(1)).mul(Jmat.Complex.sqrt(z.addr(1)))));
};
Jmat.Complex.atanh = function(z) {
// 0.5 * (ln(1+z) - ln(1-z))
return Jmat.Complex.log(z.addr(1).div(z.rsub(1))).mulr(0.5);
};
// This is NOT the logsine function (the integral). It's simply ln(sin(z))
//ln(sin(z)), with good approximation for large |Im(z)|. The thing is, for large imaginary values, sin(z) becomes huge, because it involves an exponential of the imaginary parts
// For large imaginary part (or very small below 0), log(sin(x)) fails while this function is then very accurate
Jmat.Complex.logsin = function(z) {
if(z.im > -10 && z.im < 10) return Jmat.Complex.log(Jmat.Complex.sin(z));
var ln2i = Jmat.Complex(0.69314718056, 1.570796326795); // ln(2i)
// This approximation is using a formula e^ix/2i or -e^(-ix)/2i, instead of the full (e^ix - e^(-ix) / 2i) = sin(x). This requires the real part to be exactly in range -pi/2, 3pi/2. So wrap, since it's periodic.
var p = Jmat.Complex(Jmat.Real.wrap(z.re, -Math.PI / 2, 3 * Math.PI / 2), z.im);
if(z.im > 0) return Jmat.Complex.newi(Jmat.Complex.PI).sub(Jmat.Complex.I.mul(p)).sub(ln2i);
else return Jmat.Complex.I.mul(p).sub(ln2i);
};
// See description of Jmat.Complex.logsin
Jmat.Complex.logcos = function(z) {
return Jmat.Complex.logsin(z.rsub(Math.PI / 2));
};
Jmat.Complex.floor = function(x) {
var result = Jmat.Complex(0);
result.re = Math.floor(x.re);
result.im = Math.floor(x.im);
return result;
};
Jmat.Complex.ceil = function(x) {
var result = Jmat.Complex(0);
result.re = Math.ceil(x.re);
result.im = Math.ceil(x.im);
return result;
};
Jmat.Complex.round = function(x) {
var result = Jmat.Complex(0);
result.re = Jmat.Real.round(x.re);
result.im = Jmat.Real.round(x.im);
return result;
};
// truncate towards 0
Jmat.Complex.trunc = function(x) {
var result = Jmat.Complex(0);
result.re = x.re < 0 ? Math.ceil(x.re) : Math.floor(x.re);
result.im = x.im < 0 ? Math.ceil(x.im) : Math.floor(x.im);
return result;
};
// Fractional part of x, x - floor(x). NOTE: this variant gives positive results for negative x
Jmat.Complex.frac = function(x) {
return Jmat.Complex(Jmat.Real.frac(x.re), Jmat.Real.frac(x.im));
};
// Fractional part of x, x - int(x). NOTE: this variant gives negative results for negative x
Jmat.Complex.fracn = function(x) {
return Jmat.Complex(Jmat.Real.fracn(x.re), Jmat.Real.fracn(x.im));
};
// Linear interpolation
Jmat.Complex.lerp = function(a, b, x) {
return x.rsub(1).mul(a).add(x.mul(b));
};
// Numerical note: if x.im is of the form n*pi with n a positive or negative
// integer, then the result should be real, but due to numerical imprecision
// since pi is not exactly represented may get a small (small compared to the
// magnitude of the result, that is) stray imaginary part. The caller must fix
// this on the call site if desired since the implementation here cannot know
// how near to an integer multiple of pi the caller would consider to be exact.
Jmat.Complex.exp = function(x) {
if(x.im == 0) {
return Jmat.Complex(Math.exp(x.re));
} else {
var ea = Math.exp(x.re);
return new Jmat.Complex(ea * Math.cos(x.im), ea * Math.sin(x.im));
}
};
//exp(x) - 1, with better precision for x around 0
Jmat.Complex.expm1 = function(x) {
if(x.abssq() < 1e-5) return x.add(x.mul(x).divr(2)).add(x.mul(x).mul(x).divr(6));
else return Jmat.Complex.exp(x).subr(1);
};
//natural log (base e, ln)
Jmat.Complex.log = function(x) {
if(x.eqr(-Infinity)) return Jmat.Complex(Infinity);
if(Jmat.Complex.isReal(x) && x.re >= 0) {
return Jmat.Complex(Math.log(x.re));
}
return Jmat.Complex(Math.log(x.abs()), x.arg());
};
//ln(x + 1), with better precision for x around 0
Jmat.Complex.log1p = function(x) {
if(x.abssq() < 1e-8) return x.mulr(-0.5).addr(1).mul(x);
else return Jmat.Complex.log(x.addr(1));
};
//arbitrary log: log_y(x), y is also complex number
//warning: base y is second argument
Jmat.Complex.logy = function(x, y) {
return Jmat.Complex.log(x).div(Jmat.Complex.log(y));
};
//arbitrary log: log_y(x), where y is a regular JS number
//warning: base y is second argument
Jmat.Complex.logr = function(x, y) {
return Jmat.Complex.log(x).divr(Math.log(y));
};
Jmat.Complex.log2 = function(x) {
return Jmat.Complex.log(x).divr(Math.LN2);
};
Jmat.Complex.log10 = function(x) {
return Jmat.Complex.log(x).divr(Math.LN10);
};
// Complex square root. Sqrt has two solutions, this function always returns the solution with nonnegative real part.
Jmat.Complex.sqrt = function(x) {
if(Jmat.Complex.isReal(x)) {
var result = Jmat.Complex(0);
if(x.re >= 0 || x.re != x.re) result.re = Math.sqrt(x.re);
else result.im = Math.sqrt(-x.re);
return result;
} else return x.pow(Jmat.Complex(0.5));
};
Jmat.Complex.root = function(x, y) {
return x.pow(Jmat.Complex(Jmat.Complex.inv(y)));
};