-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMaths.js
3082 lines (2925 loc) · 74.3 KB
/
Maths.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
/**
* @module Maths
* @description Maths stuff
* @version 1.0
* @since 1.1
* @license MIT
* @author Maximilian Berkmann <[email protected]>
* @copyright Maximilian Berkmann 2016
* @requires module:essence
* @requires Misc
* @requires QTest
* @requires DataStruct
* @type {Module}
* @exports Maths
*/
var Maths = new Module("Maths", "Maths stuff", ["Misc", "QTest", "DataStruct"]);
/* eslint no-undef: 0 */
/**
* @description Exclusive or
* @param {*} a Expression a
* @param {*} b Expression b
* @returns {boolean} a xor b
* @since 1.0
* @func
*/
function xor (a, b) {
return (a && !b) || (!a && b)
}
/**
* @description Converts <code>n</code> "times" to an appropriate formulation (if necessary)
* @param {number} n Number
* @returns {string} Literal
* @since 1.0
* @func
*/
function timesLiteral (n) {
switch (n) {
case 1: return "once";
case 2: return "twice";
default: return n + " times";
}
}
/**
* @description Random number generator
* @param {number} min Minimum (inclusive)
* @param {number} max Maximum (inclusive)
* @param {boolean} [integer=false] Integer or float/double
* @returns {number} Random number rad∈[<code>min</code>, <code>max</code>]
* @since 1.0
* @func
*/
function rand (min, max, integer) {
return integer? Math.floor(Math.random() * (max - min + 1) + min): Math.random() * (max - min + 1) + min; //Math.random() * (max - min) / min doesn't works for min = 0
}
/**
* @description Random number generator with 0 as the minimum
* @param {number} max Maximum (inclusive)
* @returns {number} Random number rad∈[0, <code>max</code>]
* @see module:Maths~rand
* @since 1.0
* @func
*/
function randTo (max) {
return rand(0, max, true); //To only have to use the max value and already knowing the rest
}
/**
* @description Random number generator in a specific base
* @param {number} min Minimum (inclusive)
* @param {number} max Maximum (inclusive)
* @param {number} [base=10] Base
* @param {boolean} [integer=false] Integer or float/double
* @returns {NumberLike} Random number rad<sub><code>base</code></sub>∈[<code>min</code><sub>10</sub>, <code>max</code><sub>10</sub>]
* @see module:Maths~rand
* @since 1.0
* @func
*/
function baseRand (min, max, base, integer) { //Randomise a number in the selected base
return parseFloat(rand(min, max, integer)).toString(base || 10)
}
/**
* @description Dynamic random number generator (between two variables)
* @param {number} var1 Variable #1
* @param {number} var2 Variable #2
* @param {boolean} [integer=false] Integer or float/double
* @returns {number} Random number rad∈[min(<code>var1</code>, <code>var2</code>), max(<code>var1</code>, <code>var2</code>)]
* @see module:Maths~rand
* @since 1.0
* @func
*/
function randVar (var1, var2, integer) {
return rand(Math.min(var1, var2), Math.max(var1, var2), integer); //Setting the max and min for the rand() call
}
/**
* @description Range random number generator
* @param {number} len Length of the range
* @param {boolean} [if0=false] If 0 is in the range or not
* @returns {number} Random number rad∈[0||1, <code>len</code>(-1)]
* @since 1.0
* @func
*/
function lenRand (len, if0) {
return Math.floor(Math.random() * (if0? len + 1: len)); //If the first term is 0 or 1
}
/**
* @description Random float in [0, 1] with 16-bits of randomness as Math.random() creates repetitive patterns when applied over larger space.<br />
* Source: Three.js
* @returns {number} Random float
* @since 1.0
* @func
* @see module:Maths~random
*/
function random16 () {
return (65280 * Math.random() + 255 * Math.random()) / 65535
}
/**
* @description Generate a random double in [0, 1] with <code>bits</code>-bits of randomness to avoid repetitive patterns when using Math.random() on a large spaces.
* @param {number} [bits=32] Number of bits used in the randomness
* @return {number} Random double
* @since 1.1
* @func
* @see module:Maths~random16
*/
function random (bits) {
if (!bits) bits = 32;
return ((Math.pow(2, bits) - Math.pow(2, bits / 2)) * Math.random() + (Math.pow(2, bits / 2 - 1)) * Math.random()) / (Math.pow(2, bits) - 1)
}
/**
* @description Random float in [-<code>range</code>/2, <code>range</code>/2].<br />
* Source: Three.js
* @param {number} range Range length
* @returns {number} Random float
* @since 1.0
* @func
*/
function randFloatSpread (range) {
return range * (.5 - Math.random())
}
//noinspection JSUnusedGlobalSymbols
/**
* @description Generate an array of random numbers
* @param {number} [n=10] Number of numbers
* @param {number} [min=0] Minimum
* @param {number} [max=100] Maximum
* @param {boolean} [float=true] Floating point
* @param {Bool} [base=false] Base
* @returns {Array} Random number array where ∀i∈rad, i∈[<code>min</code>, <code>max</code>]<sub>(base)</sub>
*/
function randNum (n, min, max, float, base) {
var r = [];
for (var i = 0; i < (n || 10); i++) r[i] = base? conv(rand(min || 0, max || 100, !float || true), 10, base): rand(min || 0, max || 100, !float);
return r
}
/**
* @description Generate a nearly sorted array
* @param {number} n Number of elements
* @param {number} min Minimum
* @param {number} max Maximum
* @returns {Array} Nearly sorted array
* @since 1.0
* @func
*/
function genNearlySortedArr (n, min, max) {
var aI = range(min, 1, max).slice(0, n), res = [], ic;
ic = aI.getIncrement(0);
for (var i = 0; i < aI.length; i++) {
var r = randTo(ic);
res.push(aI[i]);
if (i > 0 && r === 0) swap(res, i, i - 1);
else if (i > 1 && r === ic) swap(res, i, i - 2);
}
return res
}
/**
* @description Sum squared
* @param {number[]} arr Array of numbers
* @param {number} [nbDec=2] Number of decimals
* @returns {*} Sum squared
* @since 1.0
* @func
*/
function sumPow2 (arr, nbDec) {
if (!isType(arr, "Array")) return false;
return arr.map(function (x) {
return x * x;
}).sum().toNDec(nbDec)
}
/**
* @description Base conversion
* @param {NumberLike} n Number to convert
* @param {number} [from=2] Initial base
* @param {number} [to=10] Final base
* @param {boolean} [float=false] FPR or not
* @returns {NumberLike} Conversion: n<sub>from</sub>⇒rad<sub>to</sub>
* @since 1.0
* @func
*/
function conv (n, from, to, float) {
return float? parseFloat(n, from || 2).toString(to || 10): parseInt(n, from || 2).toString(to || 10)
}
/**
* @description Negate a binary number using 2's complement
* @param {NumberLike} bin Binary number
* @param {boolean} [toArr=false] To array
* @returns {NumberLike[]|NumberLike} Negated binary number
* @since 1.0
* @func
*/
function negateBin (bin, toArr) {
var n = [];
for(var i = 0; i < bin.length; i++) n[i] = 1 - parseInt(bin[i]);
var dec = conv(n.join(""));
dec++;
return toArr? conv(dec, 10, 2).split(""): conv(dec, 10, 2)
}
/**
* @description Floating point binary number to decimal number
* @param {string} bin Binary number
* @returns {number} Decimal number
* @since 1.0
* @func
* @throws {Error} Invalid binary number
*/
function floatingPtBin (bin) {
//%= .05859375 (sign) + .27734375 (exponent) + .6640625 (mantissa)
/* Lookup table aid
var start = new Stream(8, "x*2", 5);
table(start.data.map(function (x) {
return [(.05859375 * x), (.27734375 * x), (.6640625 * x), (.05859375 * x) + (.27734375 * x) + (.6640625 * x)];
}))
S/E/M (x2/x??/x??)
1/4/3 (8bit) -%> .125/.5/.375
1/6/9 (16bit) -%> .0625/.375/.5625
1/8/23 (32bit) -%> .03125/.25/.71875
1/11/52 (64bit) -%> .015625/.171875/.8125
1/14/112 (128bit) -%> .0078125/.109375/.875
1/x/y (Nbit) -%> .0484375/.28125/.66875 => .9984375
var start = new Stream(8, "x*2", 5);
table(start.data.map(function (x) {
return [1, (.3212890625 * x), (.6787109375 * x), (.3212890625 * x) + (.6787109375 * x)];
}))
*/
var s = (bin[0] === 1)? -1: 1, e, m, mLoop = function (x, M) {
var res = 0;
for (var i = 0; i < M; i++) res += parseInt(x[i]) * Math.pow(2, -i - 1);
return res;
}; //sign, exponent, mantissa
switch(bin.length) {
case 8:
e = ((bin[1] === 1)? 1: -1) * conv(bin.get(2, 4));
m = mLoop(bin.get(5), 3);
break;
case 16:
e = ((bin[1] === 1)? 1: -1) * conv(bin.get(2, 6));
m = mLoop(bin.get(7), 9);
break;
case 32:
e = ((bin[1] === 1)? 1: -1) * conv(bin.get(2, 8));
m = mLoop(bin.get(9), 23);
break;
case 64:
e = ((bin[1] === 1)? 1: -1) * conv(bin.get(2, 11));
m = mLoop(bin.get(12), 52);
break;
case 128:
e = ((bin[1] === 1)? 1: -1) * conv(bin.get(2, 14));
m = mLoop(bin.get(15), 112);
break;
default:
throw new Error("Invalid binary number");
}
return s * Math.pow(2, e) * m;
}
/**
* @description Minute to decimal
* @param {number} min Minutes
* @returns {number} Decimals
* @see module:Maths~dec2min
* @since 1.0
* @func
*/
function min2dec (min) { //Minute to decimal
return (50 * min) / 30
}
/**
* @description Decimal to minute
* @param {number} dec Decimals
* @returns {number} Minutes
* @see module:Maths~min2dec
* @since 1.0
* @func
*/
function dec2min (dec) {
return (30 * dec) / 50
}
/**
* @description Time to second
* @param {string} i Time ([hh:]mm:ss.xx[x])
* @returns {number} Seconds
* @see module:Maths~sec2time
* @since 1.0
* @func
*/
function toS (i) {
if (i == parseFloat(i)) return parseFloat(i);
var withH = i.count(":") === 2;
if (!i) i = withH? "00:00:00.000": "00:00.000"; //Avoid having errors
if (!isType(i, "String")) i += "";
if (i.length >= 4 && i.indexOf(":") == 1) return toS("0" + i); //So times without the leading 0 or simply with a 1-digit first section could be read properly
var t = i.split(":");
if (withH) {
var h, m, s; //Any parts that need to be extracted
h = parseInt(t[0]); //The first section: hour
m = parseInt(t[1]); //The second section: min
s = parseFloat(t[2]); //The third section: sec
return h * 3600 + m * 60 + s.toNDec();
} else {
m = parseInt(t[0]); //The first section: min
s = parseFloat(t[1]); //The second section: sec
return m * 60 + s;
}
}
/**
* @description Seconds to time
* @param {string} i Seconds
* @param {boolean} [withH=false] Include hours
* @returns {string} Time
* @see module:Maths~toS
* @since 1.0
* @func
*/
function sec2time (i, withH) {
var h = 0, m = 0, s = i;
if (withH) {
s = (i % 60).toNDigits();
h = (i >= 3600)? Math.floor(i / 3600): 0;
m = Math.floor((i - s - 3600 * h) / 60);
m = (m <= 0)? "00": m.toNDigits();
h = (h <= 0)? "00": h.toNDigits();
return h + ":" + m + ":" + s.toNDec().toNDigits(); ////Return the result as height:min:start.ms
} else {
s = (i % 60).toNDigits();
m = Math.floor(i / 60).toNDigits();
return (m <= 0)? s: m + ":" + s.toNDec().toNDigits(); //Return the result as min:start.ms
}
}
/**
* @description Alias/Shortcut
* @alias sec2time
* @since 1.0
* @func
*/
var s2t = sec2time;
/**
* @description Calculate the difference between two times.
* @param {String} [start=getTime(true)] Starting time
* @param {String} end Ending time
* @since 1.1
* @func
* @returns {string}
*/
function timeDiff (start, end) {
var withH = end.count(":") === 2;
if (!start) start = getTime(true);
if (xor(start.count(":") === 2, end.count(":") === 2)) throw new InvalidParamError("Both times needs to be in the same format");
return s2t(toS(end) - toS(start || getTime(true)), withH);
}
/**
* @description Convert a mark (out of <code>initTotal</code>) to an other (out of <code>endTotal</code>)
* @param {number} mark Mark
* @param {number} initTotal Initial total
* @param {number} [endTotal=100] Final total
* @param {number} [nbDec=2] Number of decimals
* @returns {number} Converted mark: <code>mark</code>/<code>initTotal</code> ⇒ rad/<code>endTotal</code>
* @since 1.0
* @func
*/
function markConv (mark, initTotal, endTotal, nbDec) {
return (mark / initTotal * (endTotal || 100)).toNDec(nbDec || 2)
}
/**
* @description Nth-root calculator
* @param {number} x Number
* @param {number} n Root
* @param {number} [nbDec=20] Number of decimals
* @returns {number} Nth-root
* @since 1.0
* @func
*/
function nthroot (x, n, nbDec) {
var r = getClosestRoot(x, n);
for(var i = 0; i < 60; i++) r += (x - Math.pow(r, n)) / (Math.pow(r + 1, n) - Math.pow(r, n));
return r.toNDec(nbDec || 20)
}
/**
* @description Logarithm (log<sub><code>y</code></sub>(<code>x</code>))
* @param {number} x Number
* @param {number} [y=10] Base
* @returns {number} Result
* @since 1.0
* @func
*/
function log (x, y) {
return Math.log(x) / Math.log(y || 10)
}
/**
* @description Neperian Logarithm
* @param {number} x Number
* @returns {number} Neperian logarithm
* @see module:Maths~log
* @since 1.0
* @func
*/
function ln (x) {
return log(x, Math.E);
}
/**
* @description Greatest Common Divisor
* @param {number} a Number a
* @param {number} b Number b
* @returns {number} GCD
* @since 1.0
* @func
*/
function gcd (a, b) {
return b? gcd(b, a % b): Math.abs(a)
}
//noinspection JSUnusedGlobalSymbols
/**
* @description Least Common Multiplier
* @param {number} a Number a
* @param {number} b Number b
* @returns {number} LCM
* @since 1.1
* @func
*/
function lcm (a, b) {
var multiple = a;
range(a, 1, b).forEach(function(n) {
multiple = (multiple * n) / gcd(multiple, n);
});
return multiple;
}
/**
* @description Binomial distribution X~Bin(<code>n</code>, <code>p</code>)
* @param {number} n Total number of attempts
* @param {number} p Success probability
* @param {number} r Number of attempts
* @returns {number} Binomial distribution P(x=<code>rad</code>)
* @since 1.0
* @func
*/
function Bin (n, p, r) { //Binomial distrib. where X~Bin(n, p) and it returns P(X = rad)
return C(n, r) * Math.pow(p, r) * Math.pow(1 - p, n - r)
}
/**
* @description Cumulative binomial distribution (P(X<rad)?)
* @param {number} n Total number of attempts
* @param {number} p Success probability
* @param {number} r Number of attempts
* @returns {number} Cumulative binomial distribution
* @see module:Maths~Bin
* @since 1.0
* @func
*/
function BinCumul (n, p, r) { //P(X < rad) ?
var res = [];
for (var i = 0; i < r; i++) res.push(Bin(n, p, r));
return res.sum();
}
/**
* @description Cumulative binomial distribution (P(X≤rad))
* @param {number} n Total number of attempts
* @param {number} p Success probability
* @param {number} r Number of attempts
* @returns {number} Cumulative binomial distribution
* @see module:Maths~Bin
* @since 1.0
* @func
*/
function BinCumulLT (n, p, r) { //P(X <= rad) (adapted from http://stackoverflow.com/questions/1095650/how-can-i-efficiently-calculate-the-binomial-cumulative-distribution-function)
var x = 1 - p, a = n - r, b = r + 1, c = a + b - 1, res = 0;
for (var i = a; i < c + 1; i++) res += factorial(c) / (factorial(i) * factorial(c - i)) * Math.pow(x, i) * Math.pow((1 - x), c - i);
return res;
}
/**
* @description Normal distribution Z~N(0, 1)
* @summary normalcdf(x)
* @param {number} x Number
* @returns {number} Normal distribution P(z<-abs(<code>x</code>))
* @see module:Maths~StdNorm
* @since 1.0
* @func
*/
function Norm (x) { //P(z < x) where Z~N(0, 1) (or P(z>-x) if x is positive) === normalcdf(x)
var t = 1 / (1 + .2316419 * Math.abs(x));
var d = .3989423 * Math.exp(-x * x / 2);
var p = d * t * (.3193815 + t * (-.3565638 + t * (1.781478 + t * (-1.821256 + t * 1.330274))));
return p.toNDec(4)
}
/**
* @description Standard normal distribution Z~N(<code>m</code>, <code>sd</code>)
* @param {number} m Mean
* @param {number} sd Standard deviation
* @param {number} x Number
* @returns {number} Standard normal distribution
* @see module:Maths~Norm
* @since 1.0
* @func
*/
function StdNorm (m, sd, x) {
return Norm((x - m) / sd); //P(Z<(x-m)/sd)
}
/**
* @description Inverse of Norm(rad)=<code>x</code> (Inverse Normal CDF)
* @param {number} x Normal distribution
* @return {number} rad of <code>x</code>=Norm(rad)
* @constructor
*/
function InvNorm (x) {
var a = [2.50662823884, -18.61500062529, 41.39119773534, -25.44106049637], b = [-8.47351093090, 23.08336743743, -21.06224101826, 3.13082909833], c = [.3374754822726147, .9761690190917186, .1607979714918209, .0276438810333863, .0038405729373609, .0003951896511919, .0000321767881768, .0000002888167364, .0000003960315187], y = x - .5, absY = Math.abs(y), sqY = y * y, res;
//Beasley-Springer function
if (absY < .42) res = y * (((a[3] * sqY + a[2]) * sqY + a[1]) * sqY + a[0]) / ((((b[3] * sqY +b[2]) * sqY + b[1]) * sqY + b[0]) * sqY + 1);
else { //Moro function
res = Math.log(-Math.log(y > 0? 1 - x: x));
res = c[0] + res * (c[1] + res * (c[2] + res * (c[3] + res * (c[4] + res * (c[5] + res * (c[6] + res * (c[7] + res * c[8])))))));
if (y < 0) res = -res;
}
return res;
}
/**
* @description Poisson distribution X~Po(<code>l</code>, <code>x</code>)
* @param {number} l Lambda
* @param {number} x Number
* @returns {number} Poisson distribution
* @since 1.0
* @func
*/
function Po (l, x) {
return (Math.exp(-l) * Math.pow(l, x)) / factorial(x).toNDec(4)
}
/**
* @description Cumultative poisson distribution
* @param {number} l Lambda
* @param {number} x Number
* @returns {number} Cumulative poisson distribution
* @see module:Maths~PoCumul
* @todo To revisit
* @since 1.0
* @func
*/
function PoCumul (l, x) {
/*var res = [];
for (var i = 0; i < l; i++) res.push(Po(l, x));
return res.sum();*/
return Po(l, x) * l;
}
/**
* @description factorial x!
* @param {number} x Number
* @returns {*} x!
* @since 1.0
* @func
*/
function factorial (x) {
return (x <= 1)? x: x * factorial(x - 1)
}
/**
* @description Combination/choose (∁)
* @param {number} n Total
* @param {number} r Number
* @returns {number} n∁rad
* @see module:Maths~factorial
* @since 1.0
* @func
*/
function C (n, r) {
return factorial(n) / (factorial(r) * factorial(n - r))
}
/**
* @description Binomial to Normal distribution
* @param {number} n Total number of attempts
* @param {number} p Success probability
* @param {number} r Number of attempts
* @param {string} sign Sign used in the expression
* @returns {?number} Normal distribution
* @see module:Maths~Bin
* @see module:Maths~Norm
* @since 1.0
* @func
*/
function Bin2Norm (n, p, r, sign) {
if (n * p > 5 && n * (1 - p) > 5) {
r += (sign === ">=")? -.5: .5; //Continuity correction
return StdNorm(n * p, Math.sqrt(n * p * (1 - p)), r)
} else return null;
}
/**
* @description Binomial to Poisson distribution
* @param {number} n Total number of attempts
* @param {number} p Success probability
* @param {number} r Number of attempts
* @returns {Bool} Poisson distribution
* @see module:Maths~Bin
* @see module:Maths~Po
* @since 1.0
* @func
*/
function Bin2Po (n, p, r) {
return (n > 50 && p < .1)? Po(n * p, r): false;
}
/**
* @description Poisson to Normal distribution
* @param {number} l Lambda
* @param {number} x Number
* @returns {Bool} Normal distribution
* @see module:Maths~Po
* @see module:Maths~Norm
* @since 1.0
* @func
*/
function Po2Norm (l, x) {
return (l > 10)? StdNorm(l, Math.sqrt(x), x): false;
}
/**
* @description Gaussian Error.<br />
* Source: {@link http://stackoverflow.com/questions/1095650/how-can-i-efficiently-calculate-the-binomial-cumulative-distribution-function}
* @param {number} z Number
* @returns {number} Gaussian error
* @since 1.0
* @func
*/
function erf (z) {
var t = 1/(1 + .5 * Math.abs(z)), res;
res = 1 - t * Math.exp(-z * z - 1.26551223 + t * (1.00002368 + t * ( 0.37409196 + t * ( 0.09678418 + t * (-0.18628806 + t * ( 0.27886807 + t * (-1.13520398 + t * ( 1.48851587 + t * (-0.82215223 + t * ( 0.17087277))))))))));
return z > 0? res: -res;
}
/**
* @description Normal estimate.<br />
* Source: {@link http://stackoverflow.com/questions/1095650/how-can-i-efficiently-calculate-the-binomial-cumulative-distribution-function}
* @param {number} n Total number of attempts
* @param {number} p Success probability
* @param {number} r Number of attempts
* @returns {number} Normal estimate
* @see module:Maths~erf
* @since 1.0
* @func
*/
function NormEstimate (n, p, r) {
var u = n * p, o;
o = Math.pow(u * (1 - p), .5);
return .5 * (1 + erf((r - u) / (o * Math.pow(2, .5))));
}
/**
* @description Clamp values to keep them within a range [<code>a</code>; <code>b</code>]
* @param {number} x Number
* @param {number} a Lowest bound
* @param {number} b Highest bound
* @returns {number} Clamped number
* @since 1.0
* @see module:Maths~revClamp
* @func
*/
function clamp (x, a, b) {
return (x < a)? a: ((x > b)? b: x)
}
/**
* @description Clamp values to keep them within a range ]-Inf; a]⋃[b; Inf[
* @param {number} x Number
* @param {number} a Lowest inner bound
* @param {number} b Highest inner bound
* @returns {number} Clamped number
* @since 1.0
* @see module:Maths~clamp
* @func
*/
function revClamp(x, a, b) {
return (a <= x && x <= b)? getClosest(x, [a, b]): x;
}
/**
* @description Clamp values to keep them within the range [a; Inf[
* @param {number} x Number
* @param {number} a Lowest bound
* @returns {number} Clamped value
* @see module:Maths~clamp
* @see module:Maths~clampTop
* @since 1.0
* @func
*/
function clampBottom (x, a) {
return (x < a)? a: x
}
/**
* @description Clamped values to keep them within the range ]-Inf; b]
* @param {number} x Number
* @param {number} b Highest bound
* @returns {number} Clamped valued
* @see module:Maths~clamp
* @since 1.0
* @func
*/
function clampTop (x, b) {
return (x > b)? b: x
}
/**
* @description Keeps an ascii code in the alphabetical range in the ascii table
* @param {number} code Ascii code
* @returns {number} Clamped code
* @since 1.0
* @func
*/
function abcClamp(code) {
return code === 32? 32: revClamp(clamp(code, 65, 122), 90, 97);
}
/**
* @description Linear mapping from range [<code>a1</code>; <code>a2</code>] to range [<code>b1</code>; <code>b2</code>].
* @param {number} x Number
* @param {number} a1 Lowest initial bound
* @param {number} a2 Highest initial bound
* @param {number} b1 Lowest final bound
* @param {number} b2 Highest final bound
* @returns {number} Mapped value
* @since 1.0
* @func
*/
function mapLinear (x, a1, a2, b1, b2) {
return b1 + (x - a1) * (b2 - b1) / (a2 - a1)
}
/**
* @description Degree to radiant
* @param {number} deg Degrees (°)
* @returns {number} Radiant (rad)
* @see module:Maths~rad2deg
* @since 1.0
* @func
*/
function deg2rad (deg) {
return deg * Math.PI / 180
}
/**
* @description Radiant to degree
* @param {number} rad Radiant (rad)
* @returns {number} Degree (°)
* @see module:Maths~deg2rad
* @since 1.0
* @func
*/
function rad2deg (rad) {
return rad * 180 / Math.PI
}
/**
* @description Check if <code>x</code> is a prime number
* @param {number} x Number
* @return {boolean} Primeness
* @since 1.1
* @func
*/
function isPrime (x) {
return primeN(range(1, 1, x)).has(x);
}
/**
* @description Return the prime numbers of <code>arr</code> where non prime numbers that doesn't have divisors in the array are considered prime numbers
* @param {number[]} arr Array
* @returns {Array} Prime numbers
* @see module:Maths~primeCheck
* @since 1.0
* @func
*/
function primeN (arr) {
var res = arr.quickSort();
for (var i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0 && arr[i] != 2) res[i] = "x";
for (var j = 0; j < i; j++) {
if (primeCheck(res[j], res[i])) res[i] = "x";
}
}
return res.remove()
}
/**
* @description Primeness check of <code>a</code> toward <code>b</code>
* @param {number} a Number a
* @param {number} b Number b
* @returns {boolean} Primeness
* @see module:Maths~primeN
* @since 1.0
* @func
*/
function primeCheck (a, b) {
return (a > 1 && b > 1 && b % a === 0 && b != a)
}
/**
* @description Get the closest whole <code>n</code>th-root of <code>x</code>
* @param {number} x Number
* @param {number} n Nth-root
* @returns {number} Closest root
* @since 1.0
* @func
*/
function getClosestRoot (x, n) {
if (!n) n = 2;
var rof = 0, er = 0;
if ((x / 2 * x / 2) / 2 - 2 <= x) rof = x / 2;
else if (x / 3 * x / 3 <= x) rof = x / 3;
else rof = x / 4;
if (Math.pow(rof, n) === x) return rof;
for (var p = 1; p <= n; p++) {
for (var i = 1; i < x; i++) {
if (Math.pow(i, p) === x || Math.pow(i, p - 1) * i === x) er = i;
else if (Math.pow(i, p) > x || Math.pow(i, p - 1) * i > x) er = i - .5;
}
}
if (Math.pow(er, n) <= x) return er;
else er = (Math.pow(n, -2) + x / Math.pow(n, 4)-x / Math.pow(n, 5) + Math.pow(x, n) / (Math.pow(n, Math.pow(n, 3) + 3)) + x / Math.pow(n, 2)) / 2;
if (Math.pow(er, n) > x) er = (er + rof) / 2;
var res = [rof, er, (x / er + er) / 2, (er + rof) / 2];
var resMap = res.map(function (x) {
return Math.pow(x, n);
});
return res[resMap.lookFor(getClosest(x, resMap))] * .9956973041;
}
/**
* @description Simple interest
* @param {number} po Balance
* @param {number} i Interest
* @param {number} [t=1] Time (in years)
* @returns {number} Resulting balance
* @see module:Maths~compoundInterest
* @since 1.0
* @func
*/
function simpleInterest (po, i, t) {
return po * (1 + i * (t || 1))
}
/**
* @description Compound interest
* @param {number} po Balance
* @param {number} i Interest
* @param {number} [t=1] Time (in years)
* @param {number} n Time divisions
* @returns {number} Resulting balance
* @see module:Maths~simpleInterest
* @since 1.0
* @func
*/
function compoundInterest (po, i, t, n) {
return n > 1? po * Math.pow(1 + i / n, (t || 1) * n): po * Math.pow(1 + i, (t || 1))
}
/**
* @description Everything but not 0
* @param {number} x Number
* @returns {!number} Non-null number
* @see module:essence~Essence.eps
* @since 1.0
* @func
*/
function non0 (x) {
return (x === 0)? Essence.eps: x;
}
/**
* @description Fraction form of n.<br />
* Source: somewhere
* @param {number} n Number
* @param {number} prec Precision
* @param {boolean} [up=false] Round up
* @returns {string} Fraction
* @since 1.0
* @func
*/
function toFrac (n, prec, up) {
var s = n.toString(), p = s.indexOf(".");
if (p === -1) return s;
var i = Math.floor(n) || "", dec = s.substring(p), m = prec || Math.pow(10, dec.length - 1), num = up? Math.ceil(dec * m): Math.round(dec * m), den = m,
g = gcd(num, den);
if (den / g === 1) return String(i + (num / g));
if (i) i += " and ";
return i + String(num / g) + "/" + (den / g)
}
/**
* @description Makes a number more readable
* @param {number} n Number
* @param {number} [nDec=3] Number of decimals
* @param {boolean} [usFormat=false] US format
* @returns {string} Clear number
* @since 1.0
* @func
*/
function clearNum (n, nDec, usFormat) {
var sps = (Math.floor(n) + "").length/3, str = "";
for (var i = 0; i < sps; i++) {
str = ((n - n % Math.pow(1000, i)) % Math.pow(1000, i + 1)) / Math.pow(1000, i) + " " + str;
}
str = str.split(" ");
str.pop();
return str.join(usFormat? ",": " ") + (n % 1).toNDec(nDec || 3)
}
/**
* @description Get the increment value from $a to $b
* @param {number} a Minimum
* @param {number} b Maximum
* @param {number} [nbDec] Number of decimals
* @returns {number} Step
* @see external:Array.getIncrement
* @since 1.0
* @func
*/
function getStep (a, b, nbDec) {
return [a, b].getIncrement(nbDec)
}
/**
* @description Quadratic equation solver
* @param {number} a Constant a
* @param {number} b Constant b
* @param {number} c Constant c
* @param {number} [nDec] Number of decimals
* @returns {number|NumberLike[]} Solutions
* @since 1.0
* @func
*/
function quadraticSolver (a, b, c, nDec) {
var d = Math.sqrt(b) - 4 * a * c;
return d === 0? (-b / (2 * a)).toNDec(nDec): [((-b - Math.sqrt(Math.abs(d))) / (2 * a) + (d < 0? "i": 0)).toNDec(nDec), (-b + Math.sqrt(Math.abs(d)))/(2 * a) + (d < 0? "i": 0).toNDec(nDec)]
}
/**
* @description Solve equations with a given formula and the result (end.g: x + y + x = res) and the range [<code>a</code>, <code>b</code>]
* @param {string} formula Formula
* @param {Array} res Result(start)
* @param {number} a Lowest bound
* @param {number} b Highest bound
* @returns {Array} Results