-
Notifications
You must be signed in to change notification settings - Fork 0
/
Wath.js
1308 lines (1106 loc) · 40.4 KB
/
Wath.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
class Wath {
/*=============================================
= Constants =
=============================================*/
// Threshold for accuracy as an endpoint for most integrals
static IntegrationInfinity = 2 ** 14;
static HALF_SAFE_INTEGER = Math.floor(Number.MAX_SAFE_INTEGER * 0.5);
// Most optimal dx for most common derivatives
static ACCURATE_DX = 2 ** -24;
// Good amount of steps to keep runtime ~50ms in my browser on my computer
static STANDARD_INTEGRATION_STEPS = 2 ** 20;
static standardNormalDistributions = [
{
z: -8,
area: 0.00000000000000062209605
},
{
z: -5,
area: 0.00000028665157187919391
},
{
z: -4,
area: 0.00003167124183311992125
},
{
z: -3,
area: 0.00134989803163009452665
},
{
z: -2,
area: 0.02275013194817920720028
},
{
z: -1,
area: 0.1586552539314570514148
},
{
z: -0.5,
area: 0.3085375387259868963623
},
{
z: -0.1,
area: 0.4601721627229710185346
},
{
z: 0,
area: 0.5
}
];
/*===== End of Constants ======*/
/*=============================================
= Calculus =
=============================================*/
/*---------- Derivatives ----------*/
// f(x + Δx) - f(x - Δx)
// ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
// 2 Δx
// more accurate than taking just the lefthand or righthand derivative
static derivative(funct, x, dx=this.ACCURATE_DX) {
return (funct(x + dx) - funct(x - dx))/(2*dx);
}
// f(x + Δx) - f(x)
// ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
// Δx
static rightDerivative(funct, x, dx=this.ACCURATE_DX) {
let x2 = x + dx;
let y = funct(x);
let y2 = funct(x2);
let dy = y2 - y;
return dy / dx;
}
// f(x) - f(x - Δx)
// ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
// Δx
static leftDerivative(funct, x, dx=this.ACCURATE_DX) {
return this.rightDerivative(funct, x - dx, dx);
}
static nthDerivative(funct, n, x, dx=this.ACCURATE_DX) {
if (n > 1) {
// f⁽ⁿ⁾(x) n > 1
return this.nthDerivative(funct, n-1, x, dx);
}
// f'(x)
return this.derivative(funct, x, dx);
}
/*---------- Integration ----------*/
// integral:
// ⌠ᵇ
// ⌡𝑓(𝑥)𝑑𝑥
// ᵃ
static integral(funct, a, b, steps=this.STANDARD_INTEGRATION_STEPS, minDx=this.ACCURATE_DX) {
a = Math.max(-this.IntegrationInfinity, a);
b = Math.min( this.IntegrationInfinity, b);
return this.midpointIntegral(funct, a, b, steps, minDx);
}
static midpointIntegral(funct, a, b, steps = this.STANDARD_INTEGRATION_STEPS, minDx=this.ACCURATE_DX) {
let dx = this.getStep(a, b, steps, minDx);
return this.midpointRiemann(funct, a, b, dx);
}
static trapeziumIntegral(funct, a, b, steps=this.STANDARD_INTEGRATION_STEPS, minDx=this.ACCURATE_DX) {
a = Math.max(-this.IntegrationInfinity, a);
b = Math.min( this.IntegrationInfinity, b);
let dx = this.getStep(a, b, steps, minDx);
return this.trapeziumApproximation(funct, a, b, dx);
}
// lefthand or righthand error
// ϵ ≤ |error|
// ϵ ≤ |R - L|*dx
// ϵ ≤ |f(b) - f(a)|*dx
static offhandRiemannError(funct, a, b, step=this.getStep(a, b)) {
return Math.abs(funct(b) - funct(a)) * step;
}
// midpoint error
// ϵ ≤ |error|
// ϵ ≤ |R - L|*dx / 2
// ϵ ≤ |f(b) - f(a)|*dx / 2
static midpointRiemannError(funct, a, b, step=this.getStep(a, b)) {
return Math.abs(funct(b) - funct(a)) * step / 2;
}
// get step size based on a, b, # of steps, and minDx
static getStep(a, b, steps = this.STANDARD_INTEGRATION_STEPS, minDx=this.ACCURATE_DX) {
let dx = (b - a) / steps;
return Math.max(dx, minDx);
}
// get # of steps based on a, b, minDx, and ratio from standard # of integration steps to steps
static getSteps(a, b, ratio=1, minDx=this.ACCURATE_DX) {
const range = b - a;
let steps = this.STANDARD_INTEGRATION_STEPS / ratio;
steps = Math.min(steps, range / steps);
return Math.floor(steps);
}
// takes midpoint riemann regardless of endpoints
static properIntegral(funct, a, b, steps = this.STANDARD_INTEGRATION_STEPS, minDx=this.ACCURATE_DX) {
let dx = this.getStep(a, b, steps, minDx);
return this.midpointRiemann(funct, a, b, dx);
}
static isImproperIntegral(a, b) {
return a <= -this.IntegrationInfinity || b >= this.IntegrationInfinity;
}
static improperIntegral(funct, a = -this.IntegrationInfinity, b = this.IntegrationInfinity, steps = this.STANDARD_INTEGRATION_STEPS, minDx=this.ACCURATE_DX) {
return this.nonUniformTrapeziumIntegral(funct, a, b, steps, minDx);
}
// take trapezium integral with step size varying based on change in change of funct : f⁽²⁾(x) = F⁽³⁾(x)
// currently more accurate than a midpoint riemann when the range between endpoints is large, but
// takes ~40x run-time - which means there's some error in my code or logic
static nonUniformTrapeziumIntegral(funct, a = -this.IntegrationInfinity, b = this.IntegrationInfinity, steps=this.STANDARD_INTEGRATION_STEPS, minDx=this.ACCURATE_DX) {
a = Math.max(a, -this.IntegrationInfinity);
b = Math.min(b, this.IntegrationInfinity);
const range = b - a;
const NORMAL_STEP = range / steps;
let current;
// want to know when there is change in change
// first, get change's total change
let deriv = (x) => {
return this.derivative(funct, x);
}
// get raw ugly manual map ∫ |f⁽²⁾(x)| (total change in f'(x))
const STEP_TO_TEST_STEP_RATIO = 40;
const TEST_STEP = NORMAL_STEP * STEP_TO_TEST_STEP_RATIO;
let start = a + TEST_STEP * 0.5;
current = deriv(start);
// |Δy|
let totalChange = 0;
for (let x = start + TEST_STEP; x <= b; x += TEST_STEP) {
let previous = current;
current = deriv(x);
totalChange += Math.abs(current - previous);
}
const AVERAGE_CHANGE = totalChange / range;
// console.log('this is how much the function changed');
// console.log(totalChange);
// console.log('as opposed to non-absolute integral');
// console.log(deriv(b) - deriv(a));
// console.log('derivative: ', AVERAGE_CHANGE);
const CHANGE_THRESHOLD = AVERAGE_CHANGE / steps;
let area = 0;
let step = getStep(a);
current = getVal(a);
for (let x = start + step; x <= b; x += step) {
// add to area for current step
let last = current;
current = getVal(x);
area += this.integralTrapezoid(step, last.y, current.y);
// get step
step = getStep(x);
}
return area;
function getVal(x) {
return {
x: x,
y: funct(x)
};
}
function getStep(x) {
const CHANGE_IN_CHANGE = Wath.nthDerivative(funct, 2, x);
let step = NORMAL_STEP * AVERAGE_CHANGE / CHANGE_IN_CHANGE;
step = Math.abs(step);
step = Wath.constrain(step, minDx, TEST_STEP);
return step;
}
}
/*---------- Riemann Sums + Other Approximations ----------*/
// n
// ⌠ᵇ ⎲
// ⌡𝑓(𝑥)𝑑𝑥 ≈ ⎳ 𝒇(xᵢ₋₁)Δ𝑥ᵢ
// ᵃ i=1
// steps
// ⎲
// ≈ ⎳ 𝒇(b(i/n) + a(1-i/n))dx
// i=1
static lefthandRiemann(funct, a, b, step) {
return this.loopSum(a, b - step, (x) => {
return funct(x) * step;
}, step);
}
// n
// ⌠ᵇ ⎲
// ⌡𝑓(𝑥)𝑑𝑥 ≈ ⎳ 𝒇(xᵢ+xᵢ₋₁)Δ𝑥ᵢ
// ᵃ i=1
// steps
// ⎲
// ≈ ⎳ 𝒇(b(i/n) + a(1-i/n) + dx/2)dx
// i=1
static midpointRiemann(funct, a, b, step) {
let halfStep = step * 0.5;
return this.loopSum(a + halfStep, b, (x) => {
return funct(x) * step;
}, step);
}
// n
// ⌠ᵇ ⎲
// ⌡𝑓(𝑥)𝑑𝑥 ≈ ⎳ ((𝒇(xᵢ₋₁)+f(xᵢ))/2)Δxᵢ
// ᵃ i=1
// steps
// ⎲
// ≈ ⎳ ((𝒇(b(i/n) + a(1-i/n))+𝒇(b(i/n) + a(1-i/n)+dx))/2)dx
// i=1
static trapeziumApproximation(funct, a, b, step) {
let area = 0;
let y = funct(a);
for (let x = a + step; x <= b; x += step) {
let lastY = y;
y = funct(x);
area += this.integralTrapezoid(step, lastY, y);
}
return area;
}
// trapezoid of an integral taken using the trapezium rule
static integralTrapezoid(step, y1, y2) {
return step * (y1 + y2) / 2;
}
// UNFINISHED
// keeps # of steps constant by mapping change to total change
static nonUniformRiemannConstantSteps(funct, a = -this.IntegrationInfinity, b = this.IntegrationInfinity, steps = this.STANDARD_INTEGRATION_STEPS, minDx=this.ACCURATE_DX) {
// simplify endpoints with large bounds
a = Math.max(-this.IntegrationInfinity, a); // (∞, b]
b = Math.min(this.IntegrationInfinity, b); // [a, ∞)
const range = b - a;
const NORMAL_STEP = range / steps;
// total change (∫ₐᵇ f'(x) dx)
const TOTAL_CHANGE = funct(b) - funct(a);
// return;
// take integral, using variable weighted steps
let step = minDx;
let area = 0;
for (let x = a; x < b; x += step) {
// dy / dx
let change = this.derivative(funct, x);
// abs | dy / dx |
let absChange = Math.abs(change);
// absChange = Math.min(this.IntegrationInfinity, absChange);
// // abs | dy |
// changeValue = absChange * Wath.ACCURATE_DX;
// | dx / dy |
// let changeValue = 1 / absChange;
// if (changeValue > TOTAL_CHANGE) {
// console.error('UH OH BIG CHANGE');
// console.error(x, changeValue);
// }
// step = this.map(changeValue, 0, TOTAL_CHANGE, 0, range);
// dy / dx * (normal dx)
// dy
let dy = absChange * NORMAL_STEP;
// 1 / dy
step = 1 / dy;
// dx ≤ step ≤ range
step = this.constrain(step, minDx, range);
// if (step <= 0) {
// console.error('UH OH BAD STEP');
// console.error(x, step);
// }
// step ≥ minDx
// step = Math.max(step, minDx);
area += funct(x) * step;
}
return area;
}
// broken and bad
// riemann sum with step size inversely proportional to funct's derivative (second derivative of integral)
static nonUniformRiemann(funct, a = -this.IntegrationInfinity, b = this.IntegrationInfinity, steps = this.STANDARD_INTEGRATION_STEPS, minDx=this.ACCURATE_DX) {
// simplify endpoints with large bounds
a = Math.max(-this.IntegrationInfinity, a); // (∞, b]
b = Math.min(this.IntegrationInfinity, b); // [a, ∞)
const range = b - a;
const NORMAL_STEP = range / steps;
// take integral, using variable weighted steps
let step = NORMAL_STEP;
let area = 0;
for (let x = a; x < b; x += step) {
// dy / dx
let change = this.derivative(funct, x);
// abs | dy / dx |
let absChange = Math.abs(change);
// dx / dy
let invChange = 1 / absChange;
// (scale) * dx / dy
let scaledDx = NORMAL_STEP * invChange;
// dx ≤ step ≤ range
step = this.constrain(dx, minDx, range);
area += funct(x) * step;
}
return area;
}
// no epsilon cushion, finds exact constant or uses max # of calls
// find inverse f⁻¹(target) within a and b
// returns random match if f(x) = target for multiple x values between a and b
static inverseFunct(funct, target=0, a=-this.IntegrationInfinity, b=this.IntegrationInfinity, closest=NaN, calls=2**10) {
if (calls <= 0) {
return closest;
}
// f(a)
let fOfA = funct(a);
// f(b)
let fOfB = funct(b);
let guess;
// if target is between fOfA and fOfB
if (this.between(target, fOfA, fOfB)) {
guess = this.map(target, fOfA, fOfB, a, b);
}
// if target is not between fOfA and fOfB
else {
let range = b - a;
let step = range / calls;
guess = a + step;
}
let result = funct(guess);
if (result === target) {
return guess;
}
let epsilon = Math.abs(target - result);
if (epsilon < funct(closest) || isNaN(closest)) {
closest = guess;
}
// if f(guess) between [f(a), target]
if (this.between(result, fOfA, target)) {
b = guess;
}
// if target between [guess, b]
else {
a = guess;
}
return this.inverseFunct(funct, target, a, b, closest, calls - 1);
}
// ∫ |f'(x)|dx : total change f(x) undergoes
// ∑|f(cₙ) - f(cₙ₋₁)| for all cₙ = critical value
static totalChange(funct, a=-this.IntegrationInfinity, b=this.IntegrationInfinity, steps=this.getSteps(a, b, 100)) {
// find all critical points
throw 'gotta make this function';
}
/*===== End of Calculus ======*/
/*=============================================
= Probability =
=============================================*/
static combination(n, r) {
return this.permutation(n, r) / this.factorial(r);
}
static permutation(n, r) {
return this.factorial(n) / this.factorial(n - r);
}
static factorial(n) {
if (n > 0) {
return n * this.factorial(n - 1);
}
if (n < 0 || !Number.isInteger(n)) {
return null;
}
return 1;
}
static mean(values) {
if (!Array.isArray(values)) {
return this.mean([...arguments]);
}
if (values.length <= 0) {
return 0;
}
let total = 0;
values.forEach(value => {
total += value;
});
return total / values.length;
}
/*---------- Discrete ----------*/
// binomial probability mass function :
// 𝑷(𝑿=x) = ₙ𝑪ₓ∙pˣ∙(1-p)⁽¹⁻ˣ⁾
// params: n=# of trials, p=𝑷(𝑿=x), x
static binomialpmf(n, p, x) {
return this.combination(n, x) * p ** x * (1 - p) ** (n - x);
}
// binomial cumulative mass function :
// 𝑓(x) = 𝑷(𝑿≤x) = ∀𝑿≤x Σ ₙ𝑪ₓ∙pˣ∙(1-p)⁽¹⁻ˣ⁾
// params: n=# of trials, p=𝑷(𝑿=x), x
static binomialcmf(n, p, x) {
if (x < 0) {
return 0;
}
return this.binomialpmf(n, p, x) + this.binomialcmf(n, p, x - 1);
}
static binomialMean(a, b, p, step = 1) {
let n = (b - a) / step;
return n - p;
}
static binomialVariance(a, b, p, step = 1) {
let n = (b - a) / step;
return n * p * (1 - p);
}
static binomialDeviation(a, b, p, step = 1) {
return this.binomialVariance(a, b, p, step) ** 0.5;
}
// poisson probability mass function :
// 𝑷(𝑿=x) = ( (λ∙𝑻)ˣ∙e⁻⁽λ*𝑻⁾ ) /x!
// params: λ=rate, x, T=units
// OR params: λ*T, x
static poissonpmf(lambda, x, T) {
if (!T) {
T = 1;
}
return (((lambda * T) ** x) * Math.E ** (- lambda * T)) / this.factorial(x);
}
// poisson cumulative mass function :
// 𝑓(x) = 𝑷(𝑿≤x) = ∀𝑿≤x Σ ( (λ∙𝑻)ˣ∙e⁻⁽λ*𝑻⁾ ) /x!
// params: λ=rate, x, 𝑻=units
// OR params: λ*𝑻, x
static poissoncmf(lambda, x, T) {
if (x < 0) {
return 0;
}
return this.poissonpmf(lambda, x, T) + this.poissoncmf(lambda, x - 1, T);
}
// create discrete probabilistic mean from arguments
static discreteMean(probabilities) {
if (!Array.isArray(probabilities)) {
return this.discreteMean([...arguments]);
}
if (probabilities.length <= 0) {
return 0;
}
let probability = probabilities.splice(0, 1)[0];
return probability.x * probability.p + this.discreteMean(probabilities);
}
// calculate variance of arguments
static discreteVariance(probabilities) {
if (!Array.isArray(probabilities)) {
probabilities = [...arguments];
}
if (!probabilities.length) {
return 0;
}
let probability = probabilities.splice(0, 1)[0];
return (probability.x ** 2 - probability.x) * probability.p + this.discreteVariance(probabilities);
}
// standard deviation :
// ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
// σ = 𝑽(x)² = ⎷ ∀ₓΣ (x²-x)∙p(x)
// params: probabilities
static discreteDeviation(probabilities) {
if (!Array.isArray(probabilities)) {
probabilities = [...arguments];
}
return Math.sqrt(this.discreteVariance(probabilities));
}
static discreteUniformMean(a, b) {
return (a + b) / 2;
}
static discreteUniformVariance(a, b, step = 1) {
let n = (b - a) / step;
return ((n * n - 1) / 12) * step;
}
static discreteUniformDeviation(a, b, step = 1) {
return this.discreteUniformVariance(a, b, step) ** 0.5;
}
// create probability :
// params: x, p(x)
static createProbability(x, p) {
return {
x: x,
p: p
};
}
/*---------- Continuous ----------*/
// ⌠ᵇ
// ⌡ₐ x * f(x)𝑑𝑥
static continuousMean(funct, a = -this.IntegrationInfinity, b = this.IntegrationInfinity) {
return this.integral((x) => {
return x * funct(x);
}, a, b);
}
// ⌠ᵇ ⌠ᵇ
// ⌡ₐ x² * f(x)𝑑𝑥 - ⌡ₐ x² * f(x)𝑑𝑥
// V(x) = σ² = E(X²) - μ²
static continuousVariance(funct, a = -this.IntegrationInfinity, b = this.IntegrationInfinity) {
// E(X²)
let eXSq = this.integral((x) => {
return x * x * funct(x);
}, a, b);
// E(X²) - μ²
return eXSq - this.continuousMean(funct, a, b) ** 2;
}
// σ = √V(X)
static continuousDeviation(funct, a = -this.IntegrationInfinity, b = this.IntegrationInfinity) {
return this.continuousVariance(funct, a, b) ** 0.5;
}
// continuous cumulative distribution function:
// ⌠ᵇ
// ⌡ₐ f(x)𝑑𝑥
static continuouscdf(funct, a = -this.IntegrationInfinity, b = this.IntegrationInfinity) {
return this.integral(funct, a, b);
}
// continuous uniform probability density function:
// ∀c₁,c₂∈ X ∈ [a, b] (f(c₁) = f(c₂))
// f(x) = 1 / (b - a)
static continuousUniformpdf(a = -Infinity, b = Infinity) {
return 1 / (b - a);
}
// continuous uniform cumulative density function:
// ⌠ˣ
// ⌡ₐ f(x)𝑑𝑥
// ⌠ˣ __1__
// = ⌡ₐ b - a 𝑑𝑥
// __x__ ⎢ˣ
// = b - a ⎢ₐ
// = (x-a) / (b-a)
static continuousUniformcdf(x, a = -Infinity, b = Infinity) {
if (x < a) {
return 0;
}
if (x > b) {
return 1;
}
return (x - a) / (b - a);
}
// continuous uniform mean:
// ⌠ᵇ
// ⌡ₐ x * f(x)𝑑𝑥
// ⌠ᵇ __x__
// = ⌡ₐ b - a 𝑑𝑥
// __x²___ ⎢ᵇ
// = 2(b-a) ⎢ₐ
// _b²_-_a²_
// = 2(b-a)
// = (b + a) / 2
static continuousUniformMean(a, b) {
return (a + b) / 2;
}
// continuous uniform variance:
// ⌠ᵇ ⎧⌠ᵇ ⎫²
// ⌡ₐ x² * f(x)𝑑𝑥 - ⎩⌡ₐ x * f(x)𝑑𝑥⎭
// = (b - a)² / 12
static continuousUniformVariance(a, b) {
return ((b - a) ** 2) / 12;
}
// continuous uniform deviation:
// σ = √V(x)
// = (b - a) / √12
static continuousUniformDeviation(a, b) {
return (b - a) / 12 ** 0.5;
}
/*---------- Normal Distribution ----------*/
// normal probability density function:
// (-(x-μ)² / (2σ²))
// N(μ, σ²) = e^
// ⎯⎯⎯⎯⎯
// √2πσ
// more accurate to standardize then take pdf f(z) (normalpdf)
static actualNormalpdf(x, mean, deviation) {
// -(x-μ)²
let exponentNumerator = -1 * (x - mean) ** 2;
// 2σ²
let exponentDenominator = 2 * deviation ** 2;
// -(x-μ)² / (2σ²)
let exponent = exponentNumerator / exponentDenominator;
// e^(-(x-μ)² / (2σ²))
let numerator = Math.E ** exponent;
// √2πσ
let denominator = (2 * Math.PI * deviation) ** 0.5;
// ( e^(-(x-μ)² / (2σ²)) ) / √2πσ
return numerator / denominator;
}
// normal cumulative density function:
// ⌠ᵇ
// ⌡ₐ N(μ, σ²)𝑑𝑥
// more accurate to standardize then take cdf Φ(z) (normalcdf)
static actualNormalcdf(a = -Infinity, b = Infinity, mean, deviation) {
// finite bounds
// x ∈ [finite a, finite b]
if (a > -this.IntegrationInfinity && b < this.IntegrationInfinity) {
// cdf(a, b)
return this.integral(x => {
return this.actualNormalpdf(x, mean, deviation);
}, a, b);
}
// infinite lower, finite upper
// x ∈ (-∞, finite b]
if (a < -this.IntegrationInfinity + 1 && b < this.IntegrationInfinity) {
if (b > mean) {
// cdf(-∞, μ) + cdf(μ, b)
return 0.5 + this.actualNormalcdf(mean, b, mean, deviation);
} else {
// cdf(-∞, μ) - cdf(μ, b)
return 0.5 - this.actualNormalcdf(b, mean, mean, deviation);
}
}
// finite lower, infinite upper
// x ∈ [finite a, ∞)
if (a > -this.IntegrationInfinity && b > this.IntegrationInfinity - 1) {
if (a > mean) {
// cdf(-∞, μ) - cdf(μ, a)
return 0.5 - this.actualNormalcdf(mean, a, mean, deviation);
} else {
// cdf(-∞, μ) + cdf(μ, a)
return 0.5 + this.actualNormalcdf(a, mean, mean, deviation);
}
}
// infinite bounds
// x ∈ (-∞, ∞)
return 1;
}
// standardize then take cdf Φ(z)
static normalcdf(a = -Infinity, b = Infinity, mean = 0, deviation = 1) {
return this.standardNormalcdf(this.standardizeNormal(a, mean, deviation), this.standardizeNormal(b, mean, deviation));
}
// standardize then take cdf f(z)
static normalpdf(x, mean = 0, deviation = 1) {
return this.standardNormalpdf(this.standardizeNormal(x, mean, deviation));
}
// (-z² /2)
// e^
// p(z) = ⎯⎯⎯
// √2π
static standardNormalpdf(z) {
// -z² /2
let exponent = (-1 * z ** 2) / 2;
// e^(-z² /2)
let numerator = Math.E ** exponent;
// √2π
let denominator = (2 * Math.PI) ** 0.5;
// e^(-z² /2) / √2π
return numerator / denominator;
}
// standard normal cumulative density function:
// ⌠ᵇ
// Φ(z) = ⌡ₐ p(z)𝑑z
// more accurate to standardize then take cdf Φ(z) (normalcdf)
static standardNormalcdf(a = -Infinity, b = Infinity) {
// finite bounds
// x ∈ [finite a, finite b]
if (a > -this.IntegrationInfinity && b < this.IntegrationInfinity) {
// cdf(a, b)
return this.integral(x => {
return this.standardNormalpdf(x);
}, a, b);
}
// infinite lower, finite upper
// x ∈ (-∞, finite b]
if (a < -this.IntegrationInfinity + 1 && b < this.IntegrationInfinity) {
if (b > 0) {
// cdf(-∞, b) = cdf(-∞, 0) + cdf(0, b)
return 0.5 + this.standardNormalcdf(0, b);
} else {
// cdf(-∞, b) = cdf(-∞, 0) - cdf(0, b)
return 0.5 - this.standardNormalcdf(b, 0);
}
}
// finite lower, infinite upper
// x ∈ [finite a, ∞)
if (a > -this.IntegrationInfinity && b > this.IntegrationInfinity - 1) {
if (a > 0) {
// cdf(-∞, a) = cdf(-∞, 0) - cdf(0, a)
return 0.5 - this.standardNormalcdf(0, a);
} else {
// cdf(-∞, a) = cdf(-∞, 0) + cdf(0, a)
return 0.5 + this.standardNormalcdf(a, 0);
}
}
// infinite bounds
// x ∈ (-∞, ∞)
return 1;
}
// find x given F(x)
static inverseNormal(area, mean = 0, deviation = 1) {
let z = this.inverseStandardNormal(area);
return this.unstandardizeNormal(z, mean, deviation);
}
// find z given Φ(z)
static inverseStandardNormal(area) {
if (area > 1) {
return;
}
let total;
let start, max;
// area < 0.5
for (let i = 1; i < this.standardNormalDistributions.length && !total; i++) {
if (this.standardNormalDistributions[i].area > area) {
max = this.standardNormalDistributions[i].z;
start = this.standardNormalDistributions[i - 1].z;
total = this.standardNormalDistributions[i - 1].area;
}
}
// area > 0.5
for (let i = 1; i < this.standardNormalDistributions.length && !total; i++) {
if ((1 - this.standardNormalDistributions[i].area) < area) {
max = - this.standardNormalDistributions[i - 1].z;
start = -1 * this.standardNormalDistributions[i].z;
total = 1 - this.standardNormalDistributions[i].area;
}
}
// gap between [0.5 - ϵ, 0.5 + ϵ]
if (Math.abs(0.5 - area) <= this.standardNormalDistributions[0].area) {
max = -1 * this.standardNormalDistributions[this.standardNormalDistributions.length - 2].z;
start = this.standardNormalDistributions[this.standardNormalDistributions.length - 2].z;
total = this.standardNormalDistributions[this.standardNormalDistributions.length - 2].area;
}
// if x = 0 + ϵ or 1 - ϵ
if (!total) {
if (area > 0) {
return Infinity;
} else {
return -Infinity;
}
}
// end
// ⌠
// integrate ⌡𝑓(𝑥)𝑑𝑥 ; check each step to see if z crossed
// start
let steps = this.STANDARD_INTEGRATION_STEPS;
let dx = Math.max((max - start) / steps, this.ACCURATE_DX);
for (let z = start + dx * 0.5; z < max; z += dx) {
total += this.standardNormalpdf(z) * dx;
if (total > area) {
return z - dx * 0.5;
}
}
}
// standardizing a normal random variable:
// z = (x - μ) / σ
static standardizeNormal(x, mean, deviation) {
return (x - mean) / deviation;
}
// destandardizing a standard normal random variable:
// x = (z × σ) + μ
static unstandardizeNormal(z, mean, deviation) {
return z * deviation + mean;
}
/*---------- Exponential ----------*/
// exponential probability mass function:
// -λx
// f(x) = λ · e^
static exponentialpdf(lambda, x) {
return lambda * Math.E ** (- lambda * x);
}
// exponential cumulative distribution function:
// -λx
// F(x) = 1 - e^
static exponentialcdf(lambda, x) {
return 1 - Math.E ** (- lambda * x)
}
// exponential mean:
// μ = 1 / λ
static exponentialMean(lambda) {
return 1 / lambda;
}
// exponential variance:
// V(x) = 1 / λ²
static exponentialVariance(lambda) {
return 1 / lambda ** 2;
}
// exponential deviation:
// σ = 1 / λ
static exponentialDeviation(lambda) {
return 1 / lambda;
}
/*===== End of Probability ======*/
/*=============================================
= Statistics =
=============================================*/
// I just started the statistics part of my probability & statistics class, everything in this section will definitely be updated as I learn the ropes
/*---------- Discrete ----------*/
// prob will need to rename, just the sum of all values / # of values
// ⎲
// μ = ⎳ xᵢ ÷ N
static discreteFairMean(values) {
if (!Array.isArray(values)) {
return this.discreteFairMean([...arguments]);
}
if (values.length <= 0) {
throw "what's the mean of nothing?"
}
let total = this.arraySum(values);
return total / values.length;
}
// ⎲
// μ = ⎳ xᵢ ÷ N
static populationMean(population) {
if (!Array.isArray(population)) {
population = [...arguments];
}
return this.discreteFairMean(population);
}
// N
// ⎛⎲ ⎞
// σ² = ⎳ (xᵢ-μ)² ÷ N
// ⎝i=1 ⎠
static populationVariance(population) {
if (!Array.isArray(population)) {
return this.populationVariance([...arguments]);
}
if (population.length <= 0) {
throw "what's the variance of nothing?"
}
// μ
let mean = this.populationMean(population);
let total;
population.forEach(value => {
total += (value - mean)**2;
});
return total / population.length;
}
// σ = √σ²
static populationDeviation(population) {
if (!Array.isArray(population)) {
population = [...arguments];
}
// σ = √σ²
return this.populationVariance(population) ** 0.5;
}
// __ ⎲
// X = ⎳ xᵢ ÷ n
static sampleMean(samples) {
if (!Array.isArray(samples)) {
samples = [...arguments];
}
return this.discreteFairMean(samples);
}
// n
// ⎛⎲ __ ⎞