-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathjmat_real.js
2027 lines (1764 loc) · 65 KB
/
jmat_real.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
/** @license
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: no dependencies, most basic file of jmat.js.
/*
Jmat.Real: real math operating on plain JS numbers. Similar to JS's Math library except with more functions and algorithms.
Aliased as simply "Real" by jmat.js - disable that if it causes name clashes
Overview of some functionality:
-most standard Math functions are also copied in here
-polyfill for functions of higher versions of JavaScript: Real.log2, Real.log10, Real.clz32, ...
-mod and remainder: Real.mod, Real.rem, Real.wrap, Real.clamp
-special functions. Real.gamma, Real.erf, Real.erfc, Real.lambertw, ...
-primes and factors: Real.isPrime, Real.eratosthenes, Real.factorize, Real.nextPrime, Real.previousPrime, Real.nearestPrime, Real.eulerTotient, Real.gcd, Real.lcm
-date and time: Real.isLeapYear, Real.dayOfWeek,
*/
/** @constructor
Namespace for all of Jmat. Defined in jmat_real.js as this is the first js file that everything else depends on.
*/
function Jmat() {
// Empty, this is a namespace, no need to ever call this
}
/** @constructor
namespace for real functions
*/
Jmat.Real = function() {
};
// cast all known numeric types to JS number
Jmat.Real.cast = function(v) {
if(v && v.re != undefined) return v.re;
if(v == undefined) return 0;
return v;
};
// cast all known numeric types to JS number, but only if real (so complex/imag gives NaN)
Jmat.Real.caststrict = function(v) {
if(v && v.re != undefined) return v.im == 0 ? v.re : NaN;
if(v == undefined) return 0;
return v;
};
Jmat.Real.PI = Math.PI;
Jmat.Real.E = Math.E;
Jmat.Real.SQRT2 = Math.sqrt(2);
Jmat.Real.SQRTPI = Math.sqrt(Math.PI); // gamma(0.5)
Jmat.Real.INVSQRT2PI = 1 / Math.sqrt(2 * Math.PI); //0.3989422804014327
Jmat.Real.EM = 0.57721566490153286060; // Euler-Mascheroni constant, aka Euler's gamma
Jmat.Real.APERY = 1.2020569; // Apery's constant, zeta(3)
Jmat.Real.BIGGESTJSINT = 9007199254740992; // largest number that JS (float64) can represent as integer: 2^53, 0x20000000000000, 9007199254740992
Jmat.Real.BIGGESTJSPRIME = 9007199254740881; // largest prime number that JS (float64) can represent as integer, that is, the biggest prime smaller than Jmat.Real.BIGGESTJSINT.
////////////////////////////////////////////////////////////////////////////////
// Categories
////////////////////////////////////////////////////////////////////////////////
Jmat.Real.isInt = function(x) {
return x == Math.floor(x);
};
Jmat.Real.isPositiveInt = function(x) {
return x == Math.floor(x) && x > 0;
};
Jmat.Real.isNegativeInt = function(x) {
return x == Math.floor(x) && x < 0;
};
Jmat.Real.isPositiveIntOrZero = function(x) {
return x == Math.floor(x) && x >= 0;
};
Jmat.Real.isNegativeIntOrZero = function(x) {
return x == Math.floor(x) && x <= 0;
};
// x is odd integer
Jmat.Real.isOdd = function(x) {
return Jmat.Real.isInt(x) && (x & 1) == 1;
};
// x is even integer
Jmat.Real.isEven = function(x) {
return Jmat.Real.isInt(x) && (x & 1) == 0;
};
// x is power of two
Jmat.Real.isPOT = function(x) {
return x != 0 && (x & (x - 1)) == 0;
};
Jmat.Real.isInf = function(x) {
return x == Infinity || x == -Infinity;
};
Jmat.Real.isNaN = function(x) {
return isNaN(x);
};
//isnanorinf isinfornan
Jmat.Real.isInfOrNaN = function(x) {
return x == Infinity || x == -Infinity || isNaN(x);
};
////////////////////////////////////////////////////////////////////////////////
// dist, cheb and manhattan all return regular real JS numbers for all types. In some types they are all the same, but not for e.g. Complex or Matrix.
// Euclidean distance
Jmat.Real.dist = function(a, b) {
if(a == b) return 0; // this is to avoid subtracting Infinity - Infinity
return Math.abs(a - b);
};
//Chebyshev distance
Jmat.Real.cheb = function(a, b) {
return Jmat.Real.dist(a, b);
};
//Manhattan distance
Jmat.Real.manhattan = function(a, b) {
return Jmat.Real.dist(a, b);
};
// Modulo operation. Different than JS's % operator in case of negative operands.
// Result has the sign of the divisor b.
// Works for non-integers too, similar to "fmod" in C (in case of positive arguments).
// Compare with rem: Different programs and programming languages use different
// names for this, there is no convention which one has which sign, though in
// languages with both a "mod" and "rem", the convention adopted here is most
// popular. See the table at https://en.wikipedia.org/wiki/Modulo_operation.
//
// mod in terms of rem (%). The table below compares the two operators.
// x : -4 -3 -2 -1 0 1 2 3 4
// x mod 3: 2 0 1 2 0 1 2 0 1
// x mod -3: -1 0 -2 -1 0 -2 -1 0 -2
// x rem 3: -1 0 -2 -1 0 1 2 0 1
// x rem -3: -1 0 -2 -1 0 1 2 0 1
// The sign of mod is that of b, while that of rem is that of a.
//
// "mod" is the one that is mathematically more useful, while "rem" is the one
// matching the "%" operator in most programming languages.
// mod corresponds to floored division, while rem corresponds to truncated division.
Jmat.Real.mod = function(a, b) {
return a - Math.floor(a / b) * b; // alternative: (b + (a % b)) % b
};
// Remainder. This is the same as the % operator.
// Result has the sign of the dividend a.
// Compare with Jmat.Real.mod, which is different and contains more description about the difference between rem and mod.
Jmat.Real.rem = function(a, b) {
return a % b;
};
// to is not included in the range
Jmat.Real.wrap = function(x, from, to) {
if(from == to) return from;
var m0 = Math.min(from, to);
var m1 = Math.max(from, to);
return m0 + Jmat.Real.mod(x - m0, m1 - m0);
};
// to is included in the range
Jmat.Real.clamp = function(x, from, to) {
var m0 = Math.min(from, to);
var m1 = Math.max(from, to);
return Math.max(m0, Math.min(m1, x));
};
// floored integer division. Note that this is distinct from the truncated integer division used on many platforms.
Jmat.Real.idiv = function(a, b) {
return Math.floor(a / b);
};
//Inspired by Wikipedia, Lanczos approximation, precision is around 15 decimal places
Jmat.Real.gamma = function(z) {
// Return immediately for some common values, to avoid filling the cache with those
if(z == Infinity) return Infinity;
if(z == -Infinity) return NaN;
if(Jmat.Real.useFactorialLoop_(z - 1)) {
return Jmat.Real.factorial(z - 1); //that one uses memoization
}
if(z == 0.5) return Jmat.Real.SQRTPI;
if(z > 200) return Infinity; // too large to hold in double precision. Prevent returning NaN.
// The internal function that doesn't do internal checks
var gamma_ = function(z) {
if(z <= 0 && z == Math.round(z)) return /*NaN*/ Infinity; //gamma not defined for negative integers. TODO: this should be "undirected" infinity
// reflection formula
if(z < 0.5) {
return Math.PI / (Math.sin(Math.PI * z) * gamma_(1 - z));
}
var g = 7;
var p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028,
771.32342877765313, -176.61502916214059, 12.507343278686905,
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7];
z -= 1;
var x = p[0];
for(var i = 1; i < g + 2; i++) {
x += p[i] / (z + i);
}
var t = z + g + 0.5;
return Math.sqrt(Math.PI * 2) * Math.pow(t, z + 0.5) * Math.exp(-t) * x;
};
return gamma_(z);
};
//natural logarithm of the absolute value of the gamma function
//NOTE: differs from Jmat.Complex.loggamma for negative real numbers whose truncated integer part is even, such as -4.5 or -22.5 (values where the gamma function is negative): the imaginary part is removed, log of absolute value is taken instead.
//to use this for log2 of the factorial, use e.g.: function log2fac(n) { return Jmat.Real.loggamma(n + 1) / Math.log(2); }
Jmat.Real.loggamma = function(z) {
//the result is way too imprecise if z is < 0, use the log of the reflection formula
// loggamma(z) = log(pi/sin(pi*z)) - loggamma(1 - z)
if(z < 0) {
if(z == Math.floor(z)) return Infinity;
var l = Math.log(Math.PI / Math.abs((Math.sin(Math.PI * z))));
return l - Jmat.Real.loggamma(1 - z);
}
if(z == 1 || z == 2) return 0;
if(z == Infinity) return Infinity;
if(z == -Infinity) return NaN;
// The series below has a weird artefact for values near 0 and > 0. Use actual log(gamma) for that
if(z < 1 && z >= 0) return Math.log(Math.abs(Jmat.Real.gamma(z)));
// We also get more precision still from the real formula for roughly |z| < 20
if(z > -20 && z < 20) return Math.log(Math.abs(Real.gamma(z)));
// stirling series
var result = 0.918938533204672669540968854562; //0.5 * ln(2pi)
result += (z - 0.5) * Math.log(z);
result -= z;
result += 1.0 / (z * 12);
var z3 = z * z * z;
var z5 = z3 * z * z;
var z7 = z5 * z * z;
var z9 = z7 * z * z;
result -= 1.0 / (z3 * 360);
result += 1.0 / (z5 * 1260);
result -= 1.0 / (z7 * 1680);
result += 1.0 / (z9 * 1188);
return result;
// Some other approximations for illustration only. They work worse.
// Should approximate it in theory, but does not work well numerically
/*var result = z * Math.log(z) - z + 0.5 * Math.log(2 * Math.PI / z);
for(var i = 1; i < 8; i++) {
result += Jmat.Real.bernoulli[2 * i] / (2 * i * (2 * i - 1) * Math.pow(z, (i * 2 - 1)));
}*/
/*var result = z * Math.log(z) - z + 0.5 * Math.log(2 * Math.PI / z);
var a = [1, 1, 59, 29, 533, 1577, 280361, 69311, 36226519, 7178335, 64766889203, 32128227179, 459253205417, 325788932161, 2311165698322609];
var b = [12, 12, 360, 60, 280, 168, 5040, 180, 11880, 264, 240240, 10920, 13104, 720, 367200];
var zz = 1;
for(var i = 0; i < a.length; i++) {
zz *= (z + i + 1);
result += a[i] / (b[i] * zz);
}
return result;*/
/*var ln2pi = 1.83787706640934533908193770912;
var result = 0.5 * (ln2pi - Math.log(z)) + z * (Math.log(z + 1 / (12 * z - 0.1 / z)) - 1);
return result;*/
/*var ln2pi = 1.83787706640934533908193770912;
var result = ln2pi - Math.log(z) + z * (2 * Math.log(z) + Math.log(z * Jmat.Real.sinh(1 / z) + 1 / (810 * z * z * z * z * z * z)) - 2);
return result / 2;*/
};
Jmat.Real.factorialmem_ = [1]; //memoization for factorial of small integers
Jmat.Real.useFactorialLoop_ = function(x) {
return Jmat.Real.isPositiveIntOrZero(x) && x < 200;
};
Jmat.Real.factorial = function(a) {
if(!Jmat.Real.useFactorialLoop_(a)) {
return Jmat.Real.gamma(a + 1);
}
if(Jmat.Real.factorialmem_[a]) return Jmat.Real.factorialmem_[a];
var result = Jmat.Real.factorialmem_[Jmat.Real.factorialmem_.length - 1];
for(var i = Jmat.Real.factorialmem_.length; i <= a; i++) {
result *= i;
Jmat.Real.factorialmem_[i] = result;
}
return result;
};
// checks whether a is a perfect power of b, e.g. 27 is a power of 3, but 10 is not a power of 5. Negative values are not supported.
// returns 0 if not power of (or the power is 0 - that is trivial if a is 1)
// returns the positive power otherwise
Jmat.Real.isPowerOf = function(a, b) {
var R = Jmat.Real;
if(a == b) return 1;
if(b <= 0) return 0; // false
if(a <= 0) return 0; // false
if(a == 1) return 0; // true but it's 0
if(b > a) return 0; // false
if(R.isPOT(a) && R.isPOT(b)) {
var la = R.ilog2(a);
var lb = R.ilog2(b);
if(la % lb == 0) return la / lb;
return 0;
}
if(R.isPOT(a) != R.isPOT(b)) return 0; // false
if(R.isEven(a) != R.isEven(b)) return 0; // false (or a is 1)
var c = b;
// Binary search with powers.
var bs = [];
var bb = b;
var result = 1;
while(c < a) {
bs.push(bb);
c *= bb;
result *= 2;
if(c == a) return result;
bb = bb * bb;
}
if(c == Infinity) return 0;
while(bs.length > 0) {
var p = bs.pop();
if(c > a) {
c /= p;
result -= (1 << bs.length);
}
else {
c *= p;
result += (1 << bs.length);
}
if(c == a) return result;
}
return 0;
};
Jmat.Real.firstPrimes_ = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
// Initial set up shared by several of the prime test functions.
// Returns 0 if not prime, 1 if prime, NaN if problem, -1 if unknown by this function
Jmat.Real.isPrimeInit_ = function(n) {
if(n == Infinity || n != n) return NaN;
if(n != Math.round(n)) return 0;
if(n < 2) return 0;
if(n > Jmat.Real.BIGGESTJSINT) return NaN; //too large for the floating point's integer precision, result will not make sense
for(var i = 0; i < Jmat.Real.firstPrimes_.length; i++) {
if(n == Jmat.Real.firstPrimes_[i]) return 1;
if(n % Jmat.Real.firstPrimes_[i] == 0) return 0;
}
return -1;
};
//Returns 1 if prime, 0 if not prime, NaN if error. Naive slow algorithm. However, faster than miller rabin for n < 1500000
Jmat.Real.isPrimeSlow_ = function(n) {
// Ensures the number is odd and integer in supported range, tested against first known primes
var init = Jmat.Real.isPrimeInit_(n);
if(init != -1) return init;
var p = Jmat.Real.firstPrimes_[Jmat.Real.firstPrimes_.length - 1];
var s = Math.ceil(Math.sqrt(n)) + 6;
p = Math.floor(p / 6) * 6;
while(p < s) {
if(n % (p - 1) == 0 || n % (p + 1) == 0) return 0;
p += 6;
}
return 1;
};
//Deterministic Miller-Rabin primality test
//Not probabilistic, but relies on the generalized Riemann hypothesis
//Returns 1 if prime, 0 if not prime, NaN if error.
//Supposedly fast, but only faster than the naive method for n > 1500000
Jmat.Real.isPrimeMillerRabin_ = function(n) {
// Ensures the number is odd and integer in supported range, tested against first known primes
var init = Jmat.Real.isPrimeInit_(n);
if(init != -1) return init;
// Miller-Rabin test
var base;
if(n < 1373653) base = [2, 3];
else if(n < 9080191) base = [31, 73];
else if(n < 4759123141) base = [2, 7, 61];
else if(n < 1122004669633) base = [2, 13, 23, 1662803];
else if(n < 2152302898747) base = [2, 3, 5, 7, 11];
else if(n < 3474749660383) base = [2, 3, 5, 7, 11, 13];
else if(n < 341550071728321) base = [2, 3, 5, 7, 11, 13, 17];
else if(n < 3770579582154547) base = [2, 2570940, 880937, 610386380, 4130785767];
else base = [2, 325, 9375, 28178, 450775, 9780504, 1795265022]; //valid up to >2^64
var d = Math.floor(n / 2);
var s = 1;
while(!(d & 1)) {
d = Math.floor(d / 2);
++s;
}
// returns (a + b) % c, taking overflow into account (in JS, overflow means reaching a part in the floating point representation where it can no longer distinguish 1)
var modadd = function(a, b, c) {
if (a + b < Jmat.Real.BIGGESTJSINT) return (a + b) % c;
if(a + b > c) {
return (a - c + b) % c;
}
// This assumes that c < 4503599627370496 or a + b doesn't overflow
return ((a % c) + (b % c)) % c;
};
// returns (a * b) % c, taking overflow into account
var modmul = function(a, b, c) {
if(a * b < Jmat.Real.BIGGESTJSINT) return (a * b) % c;
var x = 0;
var y = a % c;
while(b > 0) {
if(b & 1) x = modadd(x, y, c);
y = modadd(y, y, c);
b = Math.floor(b / 2);
}
return x % c;
};
// returns (a to the n) % mod, taking overflow into account
var modpow = function(a, n, mod) {
var result = 1;
while(n > 0) {
if(n & 1) result = modmul(result, a, mod);//(result * a) % mod;
a = modmul(a, a, mod);//(a * a) % mod;
n = Math.floor(n / 2);
}
return result;
};
var witness = function(n, s, d, a) {
var x = modpow(a, d, n);
var y;
while(s) {
y = modmul(x, x, n); //(x * x) % n;
if(y == 1 && x != 1 && x != n - 1) return false;
x = y;
s--;
}
return y == 1;
};
for(var i = 0; i < base.length; i++) {
if(!witness(n, s, d, base[i])) return 0;
}
return 1;
};
/*
test in console for the above function:
function benchfun(n) {
var ra = 0; var ta0 = new Date().getTime(); for(var i = 0; i < n; i++) ra += Jmat.Real.isPrimeMillerRabin_(i); var ta1 = new Date().getTime();
var rb = 0; var tb0 = new Date().getTime(); for(var i = 0; i < n; i++) rb += Jmat.Real.isPrimeSlow_(i); var tb1 = new Date().getTime();
var rc = 0; var tc0 = new Date().getTime(); for(var i = 0; i < n; i++) rc += Jmat.Real.isPrime(i); var tc1 = new Date().getTime();
console.log('fast: ' + (ta1 - ta0) + ' slow: ' + (tb1 - tb0) + ' both: ' + (tc1 - tc0) + ' test: ' + ra + ' = ' + rb + ' = ' + rc);
};
benchfun(100000);
--> it will report that slow if faster than miller rabin. That's because miller rabin is only faster for very large numbers. E.g. here you can see that miller rabin is faster:
Jmat.Real.isPrimeSlow_(4444280714420857)
Jmat.Real.isPrimeMillerRabin_(4444280714420857)
function testfun(n) {
for(var i = 0; i < n; i++) {
var a = Jmat.Real.isPrimeMillerRabin_(i);
var b = Jmat.Real.isPrimeSlow_(i);
if(a != b) console.log('error: ' + i + ' ' + a + ' ' + b);
}
console.log('ok: ' + n);
};
testfun(100000);
Nice primes to test:
3770579582154547 --> NOT prime, but above this boundary, last "base" for miller rabin test is used
9007199254740992 --> NOT prime, but highest integer number that JavaScript supports
9007199254740881: just small enough for JS! ==> overflow with sum, does not work
4444280714420857: largest for half JS bits
311111111111113: for third last base
344555666677777: for second last base
*/
//Returns 1 if prime, 0 if not prime, NaN if error.
Jmat.Real.isPrime = function(n) {
// below that, the "slow" method is faster. For higher values, Miller Rabin becomes more and more significantly faster.
return (n < 1500000) ? Jmat.Real.isPrimeSlow_(n) : Jmat.Real.isPrimeMillerRabin_(n);
};
// Sieve of Eratosthenes: returns array of all the primes up to n.
Jmat.Real.eratosthenes = function(n) {
if(n < 2) return [];
var result = [2];
var a = [];
var s = Math.floor(Math.sqrt(n));
var num = Math.ceil(n / 2);
// a[i] represents odd numbers: a[0] represents 1, a[1] represents 3, a[n] represents n*2 + 1, m is represented by a[floor(m / 2)]
for(var i = 0; i < num; i++) a[i] = true;
for(var m = 3; m <= s; m += 2) {
var i = Math.floor(m / 2);
if(!a[i]) continue;
for(var j = i + m; j < num; j += m) a[j] = false;
}
for(var i = 1; i <= n; i++) {
if(a[i]) result.push((i * 2) + 1);
}
return result;
};
//for factorize
Jmat.Real.smallestPrimeFactor = function(x) {
if(x == Infinity || x != x) return NaN;
if(x != Math.round(x)) return NaN;
if(x < 1) return NaN;
if(x > Jmat.Real.BIGGESTJSINT) return NaN; //too large for the floating point's integer precision, result will not make sense
if(x == 1) return 1;
for(var i = 0; i < Jmat.Real.firstPrimes_.length; i++) {
if(x == Jmat.Real.firstPrimes_[i]) return x;
if(x % Jmat.Real.firstPrimes_[i] == 0) return Jmat.Real.firstPrimes_[i];
}
var p = Jmat.Real.firstPrimes_[Jmat.Real.firstPrimes_.length - 1];
var s = Math.ceil(Math.sqrt(x));
p = Math.floor(p / 6) * 6;
while(p < s + 5) {
if(x % (p - 1) == 0) return p - 1;
if(x % (p + 1) == 0) return p + 1;
p += 6;
}
return x;
};
//factorize: returns prime factors as array of real integers, sorted from smallest to largest. x must be integer.
Jmat.Real.factorize = function(x) {
if(x > Jmat.Real.BIGGESTJSINT) return undefined; //too large for the floating point's integer precision, will cause crash
var x = Math.round(x);
var result = [];
if(x < 0) {
x = -x;
result.push(-1);
}
if(x <= 2) {
if(result.length == 0 || x != 1) result.push(x); // return [0] if x is 0, [1] if x is 1
return result;
}
for(;;) {
if(x < 1) break;
var y = Jmat.Real.smallestPrimeFactor(x);
result.push(y);
if(x == y) break;
x = Math.round(x / y);
}
return result;
};
Jmat.Real.primeCount = function(value) {
var primesN = [ 0, 2, 3, 5, 7, 11, 13, 17 ];
// Nth prime (1-indexed: n=1 gives 2)
var p = function(n) {
if(n < primesN.length) return primesN[n];
var i = primesN[primesN.length - 1] + 2;
var count = primesN.length - 1;
for(;;) {
if(Jmat.Real.isPrime(i)) {
primesN.push(i);
count++;
if(count == n) return i;
}
i += 2;
}
};
var phiCache = {};
// number of natural numbers smaller than m which are not divisible by
// the first n primes
var phi = function(m, n) {
if(n == 0) return Math.floor(m);
else if(n == 1) return Math.floor((m + 1) / 2);
else {
if(phiCache[m] && phiCache[m][n] != undefined) return phiCache[m][n];
var result = phi(m, n - 1) - phi(Math.floor(m / p(n)), n - 1);
if(!phiCache[m]) phiCache[m] = {};
phiCache[m][n] = result;
return result;
}
};
var piCache = {};
var pi = function(v) {
if(v > 1000000000) return NaN; //it starts giving rounding errors or so somewhere before 1050000000
if(v < 2) return 0;
if(v < 3) return 1;
if(v < 5) return 2;
var n = Math.floor(v);
if(piCache[n]) return piCache[n];
var a = Math.floor(pi(Math.pow(v, 1.0 / 4.0)));
var b = Math.floor(pi(Math.sqrt(v)));
var c = Math.floor(pi(Math.pow(v, 1.0 / 3.0)));
var sum = phi(n, a) + Math.floor((b + a - 2) * (b - a + 1) / 2);
for(var i = a + 1; i <= b; i++) {
var w = n / p(i); //NOT integer division!
sum -= pi(w);
if(i <= c) {
var bi = pi(Math.sqrt(w));
for(var j = i; j <= bi; j++) {
sum -= pi(w / p(j)) - j + 1;
}
}
}
piCache[n] = sum;
return sum;
};
return pi(value);
};
Jmat.Real.nearestPrime = function(value) {
var x = Math.round(value);
// Anything below 6 does not work with the calculations below.
if(x < 7) {
if(x <= 2) return 2;
if(x <= 4) return 3;
return 5;
}
if(x == Infinity || x != x) return NaN;
if(x >= 9007199254740881) return NaN; //largest supported prime in floating point precision, after this result is not correct because after Jmat.Real.BIGGESTJSINT isPrime gives NaN
if(Jmat.Real.isPrime(x)) return x;
var d = x % 6;
var e = 6 - d;
var i = 0;
var result = 0;
for(;;) {
if(Jmat.Real.isPrime(x - i - d + 1)) result = x - i - d + 1;
else if(Jmat.Real.isPrime(x - i - d - 1)) result = x - i - d - 1;
if((!result || (x - result) > (i + e - 1)) && Jmat.Real.isPrime(x + i + e - 1)) result = x + i + e - 1;
else if((!result || (x - result) > (i + e + 1)) && Jmat.Real.isPrime(x + i + e + 1)) result = x + i + e + 1;
if(result) return result;
i += 6;
}
};
Jmat.Real.nextPrime = function(value) {
var x = Math.floor(value);
if(x < 2) return 2;
if(x < 3) return 3;
if(x == Infinity || x != x) return NaN;
if(x >= 9007199254740881) return NaN; //largest supported prime in floating point precision, after this will infinite loop because after Jmat.Real.BIGGESTJSINT isPrime gives NaN
var m = x % 6;
var step = 2;
if(m == 0 || m == 5) {
x += (m == 0 ? 1 : 2);
step = 4;
} else {
x += (5 - m);
}
for(;;) {
if(Jmat.Real.isPrime(x)) return x;
x += step;
step ^= 6; //swap step between 2 and 4
}
};
Jmat.Real.previousPrime = function(value) {
var x = Math.ceil(value);
if(x <= 2) return NaN; // there is no lower prime
if(x <= 3) return 2;
if(x <= 5) return 3;
if(x <= 7) return 5;
if(x == Infinity || x != x) return NaN;
if(x > Jmat.Real.BIGGESTJSINT) return NaN; //too large for the floating point's integer precision, result will not make sense
var m = x % 6;
var step = 2;
if(m == 0 || m == 1) {
x -= (m + 1);
step = 4;
} else {
x -= (m - 1);
}
for(;;) {
if(Jmat.Real.isPrime(x)) return x;
x -= step;
step ^= 6; //swap step between 2 and 4
}
};
Jmat.Real.eulerTotient = function(value) {
if(value <= 0) return NaN;
var n = Math.floor(value);
var f = Jmat.Real.factorize(n);
var prev = -1;
var result = n;
for(var i = 0; i < f.length; i++) {
if(prev == f[i]) continue; //must be unique factors
if(f[i] == 1) break;
prev = f[i];
result *= (1 - (1 / f[i]));
}
return result;
};
// The first integer binomials, allows fast calculation of those by just looking up in the array, e.g. binomial(5, 8) = Jmat.Complex.pascal_triangle_cache_[5][8]
// some rows area pre-filled to start it off (just pre-filling the first one would be sufficient normally, the rest is just for the shows)
Jmat.Real.pascal_triangle_cache_ = [
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1],
[1, 5, 10, 10, 5, 1],
[1, 6, 15, 20, 15, 6, 1],
[1, 7, 21, 35, 35, 21, 7, 1]
];
// A helper function for integer binomial. Uses cached pascal triangle, so is guaranteed to be O(1) once the cache is filled up.
// Only works for integers, and only works for n < 180. After that, the double precision numbers no longer recognise every integer number.
Jmat.Real.pascal_triangle = function(n, p) {
if(n < 0 || p < 0 || n < p) return NaN;
if(n > 180) return NaN; //triangle values get too big for integers in double precision floating point
//fill up cache if needed
var t = Jmat.Real.pascal_triangle_cache_;
while(t.length <= n) {
var l = t.length; //the 'n' of the new row
var l2 = l + 1; // number of elements of this new row
t[l] = [];
for(var i = 0; i < l2; i++) {
t[l][i] = (i == 0 || i == l2 - 1) ? 1 : (t[l-1][i-1] + t[l-1][i]);
}
}
return t[n][p];
};
//greatest common divisor
Jmat.Real.gcd = function(x, y) {
if(!Jmat.Real.isInt(x) || !Jmat.Real.isInt(y)) return NaN; //prevents infinite loop if both x and y are NaN. Also, reals are not supported here.
if(Math.abs(x) > Jmat.Real.BIGGESTJSINT || Math.abs(y) > Jmat.Real.BIGGESTJSINT) return NaN; // does not work above JS integer precision
//Euclid's algorithm
for(;;) {
if(y == 0) return Math.abs(x); //if x or y are negative, the result is still positive by the definition
var z = Jmat.Real.mod(x, y);
x = y;
y = z;
}
};
//least common multiple
Jmat.Real.lcm = function(x, y) {
return Math.abs(x * y) / Jmat.Real.gcd(x, y);
};
// Decomposes fraction (aka rational approximation): returns two integers [numerator, denominator] such that n/d = a.
// Very slow, too slow for inner loop of running programs (integrate or complex plot)...
// max = max value for denominator
// E.g. Jmat.Real.decompose(Math.PI, 100) gives [22, 7], because 22/7 approximates pi.
Jmat.Real.decompose = function(x, max) {
if(!max) max = 100000;
var neg = (x < 0);
if(neg) x = -x;
var f = Math.floor(x);
var y = x - f;
if(y == 0) return [x, 1]; //otherwise the loop will run max times for nothing, very inefficient
var result;
var a = 0;
var b = 1;
var c = 1;
var d = 1;
//mediant of two fractions a/c and b/d is defined as (a+b)/(c+d)
while (b <= max && d <= max) {
var mediant = (a + c) / (b + d);
if(y == mediant) {
if(b + d <= max) result = [a + c, b + d];
else if(d > b) result = [c, d];
else result = [a, b];
break;
} else if(y > mediant) {
a = a + c;
b = b + d;
} else {
c = a + c;
d = b + d;
}
}
if (!result) {
if (b > max) result = [c, d];
else result = [a, b];
}
result[0] += f * result[1];
if(neg) result[0] = -result[0];
return result;
};
// Hybrid between decompose and decomposeFast
Jmat.Real.decomposeSemiFast = function(x, max) {
var maxslow = 1000;
if(max < maxslow) {
return Jmat.Real.decompose(x, max);
} else {
var a = Jmat.Real.decompose(x, maxslow);
var ax = a[0] / a[1];
if(ax == x) return a;
var b = Jmat.Real.decomposeFast(x, maxslow);
var bx = b[0] / b[1];
return (Math.abs(x - ax) < Math.abs(x - bx)) ? a : b;
}
};
// Decomposes fraction (aka rational approximation): returns two integers [numerator, denominator] such that n/d = a.
// max = max value for denominator
// A lot faster, but less nice than Jmat.Real.decompose (e.g. returns 83333/10000 instead of 1/12), and with high preference for decimal denominators. TODO: other bases than base 10
Jmat.Real.decomposeFast = function(x, max) {
if(!max) max = 100000;
var max1 = max - 1;
if(x <= max1 && x >= -max1 && (x < -1.0 / max1 || x > 1.0 / max1)) {
var neg = (x < 0);
if(neg) x = -x;
var z = Math.floor(x);
var n = x - z;
var d = max;
n = Math.floor(n * d);
var g = Jmat.Real.gcd(n, d);
d /= g;
n /= g;
n += z * d;
if(neg) n = -n;
// n = numerator, d = denominator
return [n, d];
}
return [x, 1];
};
Jmat.Real.near = function(x, y, epsilon) {
// works also for infinities
return x >= y - epsilon && x <= y + epsilon;
};
/*
Precision must be near 0 but slightly larger, e.g. 0.001 for 3 digits of precision, 1e-5 for 5 digits, ...
That many digits must match, starting from the first non-zero digit.
That means, if one value is zero and the other is not, no matter how close to zero the other is, this function will always return false.
It also always returns false if the signs differ.
Examples:
Jmat.Real.relnear(1.25e-300, 1.26e-300, 1e-2) --> true
Jmat.Real.relnear(1.25e-300, 1.26e-300, 1e-3) --> false
*/
Jmat.Real.relnear = function(x, y, precision) {
if(x == y) return true;
if(x == 0 || y == 0) return false; // case were both are 0 already handled with previous comparison
if((x < 0) != (y < 0)) return false;
x = Math.abs(x);
y = Math.abs(y);
var d = (x > y) ? (x / y) : (y / x);
return d < 1 + precision;
};
// Fractional part of x, x - floor(x). NOTE: this variant gives positive results for negative x
Jmat.Real.frac = function(x) {
return x - Math.floor(x);
};
// Fractional part of x, x - int(x). NOTE: this variant gives negative results for negative x
Jmat.Real.fracn = function(x) {
return x > 0 ? (x - Math.floor(x)) : -(-x - Math.floor(-x));
};
// Only the principal branch for real values above -1/e
Jmat.Real.lambertw = function(x) {
if(isNaN(x)) return NaN;
if(x == Infinity || x == -Infinity) return Infinity;
if(x >= -1.0 / Math.E && x <= 703) {
//Newton's method. Only works up to 703
var wj = x < 10 ? 0 : Math.log(x) - Math.log(Math.log(x)); // Without good starting value, it requires hundreds of iterations rather than just 30.
var num = Math.max(30, x > 0 ? 10 + Math.floor(x) : 30);
for(var i = 0; i < num; i++) {
var ew = Math.exp(wj);
wj = wj - ((wj * ew - x) / (ew + wj * ew));
}
return wj;
} else if (x > 0) {
//Since the above method works only up to 703, use some kind of binary search instead (it's a monotonously increasing function at this point)
// TODO: probably just use Halley's method here instead
var step = 1;
var lastDir = 0;
var result = Math.log(x) - Math.log(Math.log(x)); // good starting value speeds up iterations. E.g. only 76 instead of 292 for 7e100.
for(;;) {
if(step == 0 || step * 0.5 == step || result + step == result) return result; //avoid infinite loop
var v = result * Math.exp(result);
if(Jmat.Real.near(v, x, 1e-15)) return result;
if(v > x) {
result -= step;
if(lastDir == -1) step *= 0.5;
lastDir = 1;
} else {
result += step;
if(lastDir == 1) step *= 0.5;
lastDir = -1;
}
}
}
return NaN;
};
//arbitrary log: log_y(x)
//warning: base y is second argument
Jmat.Real.logy = function(x, y) {
return Math.log(x) / Math.log(y);
};
// Returns the number of leading zero bits in the 32-bit binary representation of x
// Gives floor of log2 of x by doing 31 - clz32(x)
// Gives num bits of x by doing 32 - clz32(x)
// Only guaranteed to work for numbers less than 32 bits
Jmat.Real.clz32 = Math['clz32'] || function(x) {
var result = 0;
while(x > 0) {
x = Math.floor(x / 2);
result++;
}
return 32 - result;
};
//NOTE: floating point version. For integer log2 use ilog2,
//because e.g. on 8 this gives 2.9999999999999996 (official Math.log2 too)
Jmat.Real.log2 = Math.log2 || function(x) {
return Math.log(x) / Math.LN2;
};
// Integer log2: the floor of log2
Jmat.Real.ilog2 = function(x) {
if(x <= 0) return NaN;
if(x < 2147483648) return 31 - Jmat.Real.clz32(x);
return Math.floor(Jmat.Real.log2(Math.floor(x) + 0.5));
};
Jmat.Real.getNumBits = function(x) {
return Jmat.Real.ilog2(Math.abs(x)) + 1;
};
Jmat.Real.log10 = Math.log10 || function(x) {
return Math.log(x) / Math.LN10;
};
Jmat.Real.root = function(x, y) {
return Math.pow(x, 1 / y);
};
////////////////////////////////////////////////////////////////////////////////
Jmat.Real.seed = undefined;
// Uses Math.random by default, but for reproducible tests, set Jmat.Real.seed to a positive integer (max 31 bits)
Jmat.Real.random = function() {
if (Jmat.Real.seed == undefined) {
return Math.random();
}