-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple-statistics.js
4312 lines (3957 loc) · 135 KB
/
simple-statistics.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
'use strict';
/**
* ISC License
*
* Copyright (c) 2014, Tom MacWright
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
* INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
/**
* [Simple linear regression](http://en.wikipedia.org/wiki/Simple_linear_regression)
* is a simple way to find a fitted line
* between a set of coordinates. This algorithm finds the slope and y-intercept of a regression line
* using the least sum of squares.
*
* @param {Array<Array<number>>} data an array of two-element of arrays,
* like `[[0, 1], [2, 3]]`
* @returns {Object} object containing slope and intersect of regression line
* @example
* linearRegression([[0, 0], [1, 1]]); // => { m: 1, b: 0 }
*/
function linearRegression(data) {
var m, b;
// Store data length in a local variable to reduce
// repeated object property lookups
var dataLength = data.length;
//if there's only one point, arbitrarily choose a slope of 0
//and a y-intercept of whatever the y of the initial point is
if (dataLength === 1) {
m = 0;
b = data[0][1];
} else {
// Initialize our sums and scope the `m` and `b`
// variables that define the line.
var sumX = 0,
sumY = 0,
sumXX = 0,
sumXY = 0;
// Use local variables to grab point values
// with minimal object property lookups
var point, x, y;
// Gather the sum of all x values, the sum of all
// y values, and the sum of x^2 and (x*y) for each
// value.
//
// In math notation, these would be SS_x, SS_y, SS_xx, and SS_xy
for (var i = 0; i < dataLength; i++) {
point = data[i];
x = point[0];
y = point[1];
sumX += x;
sumY += y;
sumXX += x * x;
sumXY += x * y;
}
// `m` is the slope of the regression line
m =
(dataLength * sumXY - sumX * sumY) /
(dataLength * sumXX - sumX * sumX);
// `b` is the y-intercept of the line.
b = sumY / dataLength - (m * sumX) / dataLength;
}
// Return both values as an object.
return {
m: m,
b: b
};
}
/**
* Given the output of `linearRegression`: an object
* with `m` and `b` values indicating slope and intercept,
* respectively, generate a line function that translates
* x values into y values.
*
* @param {Object} mb object with `m` and `b` members, representing
* slope and intersect of desired line
* @returns {Function} method that computes y-value at any given
* x-value on the line.
* @example
* var l = linearRegressionLine(linearRegression([[0, 0], [1, 1]]));
* l(0) // = 0
* l(2) // = 2
* linearRegressionLine({ b: 0, m: 1 })(1); // => 1
* linearRegressionLine({ b: 1, m: 1 })(1); // => 2
*/
function linearRegressionLine(mb /*: { b: number, m: number }*/) {
// Return a function that computes a `y` value for each
// x value it is given, based on the values of `b` and `a`
// that we just computed.
return function (x) {
return mb.b + mb.m * x;
};
}
/**
* Our default sum is the [Kahan-Babuska algorithm](https://pdfs.semanticscholar.org/1760/7d467cda1d0277ad272deb2113533131dc09.pdf).
* This method is an improvement over the classical
* [Kahan summation algorithm](https://en.wikipedia.org/wiki/Kahan_summation_algorithm).
* It aims at computing the sum of a list of numbers while correcting for
* floating-point errors. Traditionally, sums are calculated as many
* successive additions, each one with its own floating-point roundoff. These
* losses in precision add up as the number of numbers increases. This alternative
* algorithm is more accurate than the simple way of calculating sums by simple
* addition.
*
* This runs in `O(n)`, linear time, with respect to the length of the array.
*
* @param {Array<number>} x input
* @return {number} sum of all input numbers
* @example
* sum([1, 2, 3]); // => 6
*/
function sum(x) {
// If the array is empty, we needn't bother computing its sum
if (x.length === 0) {
return 0;
}
// Initializing the sum as the first number in the array
var sum = x[0];
// Keeping track of the floating-point error correction
var correction = 0;
var transition;
for (var i = 1; i < x.length; i++) {
transition = sum + x[i];
// Here we need to update the correction in a different fashion
// if the new absolute value is greater than the absolute sum
if (Math.abs(sum) >= Math.abs(x[i])) {
correction += sum - transition + x[i];
} else {
correction += x[i] - transition + sum;
}
sum = transition;
}
// Returning the corrected sum
return sum + correction;
}
/**
* The mean, _also known as average_,
* is the sum of all values over the number of values.
* This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency):
* a method of finding a typical or central value of a set of numbers.
*
* This runs in `O(n)`, linear time, with respect to the length of the array.
*
* @param {Array<number>} x sample of one or more data points
* @throws {Error} if the length of x is less than one
* @returns {number} mean
* @example
* mean([0, 10]); // => 5
*/
function mean(x) {
if (x.length === 0) {
throw new Error("mean requires at least one data point");
}
return sum(x) / x.length;
}
/**
* The sum of deviations to the Nth power.
* When n=2 it's the sum of squared deviations.
* When n=3 it's the sum of cubed deviations.
*
* @param {Array<number>} x
* @param {number} n power
* @returns {number} sum of nth power deviations
*
* @example
* var input = [1, 2, 3];
* // since the variance of a set is the mean squared
* // deviations, we can calculate that with sumNthPowerDeviations:
* sumNthPowerDeviations(input, 2) / input.length;
*/
function sumNthPowerDeviations(x, n) {
var meanValue = mean(x);
var sum = 0;
var tempValue;
var i;
// This is an optimization: when n is 2 (we're computing a number squared),
// multiplying the number by itself is significantly faster than using
// the Math.pow method.
if (n === 2) {
for (i = 0; i < x.length; i++) {
tempValue = x[i] - meanValue;
sum += tempValue * tempValue;
}
} else {
for (i = 0; i < x.length; i++) {
sum += Math.pow(x[i] - meanValue, n);
}
}
return sum;
}
/**
* The [variance](http://en.wikipedia.org/wiki/Variance)
* is the sum of squared deviations from the mean.
*
* This is an implementation of variance, not sample variance:
* see the `sampleVariance` method if you want a sample measure.
*
* @param {Array<number>} x a population of one or more data points
* @returns {number} variance: a value greater than or equal to zero.
* zero indicates that all values are identical.
* @throws {Error} if x's length is 0
* @example
* variance([1, 2, 3, 4, 5, 6]); // => 2.9166666666666665
*/
function variance(x) {
if (x.length === 0) {
throw new Error("variance requires at least one data point");
}
// Find the mean of squared deviations between the
// mean value and each value.
return sumNthPowerDeviations(x, 2) / x.length;
}
/**
* The [standard deviation](http://en.wikipedia.org/wiki/Standard_deviation)
* is the square root of the variance. This is also known as the population
* standard deviation. It's useful for measuring the amount
* of variation or dispersion in a set of values.
*
* Standard deviation is only appropriate for full-population knowledge: for
* samples of a population, {@link sampleStandardDeviation} is
* more appropriate.
*
* @param {Array<number>} x input
* @returns {number} standard deviation
* @example
* variance([2, 4, 4, 4, 5, 5, 7, 9]); // => 4
* standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]); // => 2
*/
function standardDeviation(x) {
if (x.length === 1) {
return 0;
}
var v = variance(x);
return Math.sqrt(v);
}
/**
* The [R Squared](http://en.wikipedia.org/wiki/Coefficient_of_determination)
* value of data compared with a function `f`
* is the sum of the squared differences between the prediction
* and the actual value.
*
* @param {Array<Array<number>>} x input data: this should be doubly-nested
* @param {Function} func function called on `[i][0]` values within the dataset
* @returns {number} r-squared value
* @example
* var samples = [[0, 0], [1, 1]];
* var regressionLine = linearRegressionLine(linearRegression(samples));
* rSquared(samples, regressionLine); // = 1 this line is a perfect fit
*/
function rSquared(x, func) {
if (x.length < 2) {
return 1;
}
// Compute the average y value for the actual
// data set in order to compute the
// _total sum of squares_
var sum = 0;
for (var i = 0; i < x.length; i++) {
sum += x[i][1];
}
var average = sum / x.length;
// Compute the total sum of squares - the
// squared difference between each point
// and the average of all points.
var sumOfSquares = 0;
for (var j = 0; j < x.length; j++) {
sumOfSquares += Math.pow(average - x[j][1], 2);
}
// Finally estimate the error: the squared
// difference between the estimate and the actual data
// value at each point.
var err = 0;
for (var k = 0; k < x.length; k++) {
err += Math.pow(x[k][1] - func(x[k][0]), 2);
}
// As the error grows larger, its ratio to the
// sum of squares increases and the r squared
// value grows lower.
return 1 - err / sumOfSquares;
}
/**
* The [mode](https://en.wikipedia.org/wiki/Mode_%28statistics%29) is the number
* that appears in a list the highest number of times.
* There can be multiple modes in a list: in the event of a tie, this
* algorithm will return the most recently seen mode.
*
* This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency):
* a method of finding a typical or central value of a set of numbers.
*
* This runs in `O(n)` because the input is sorted.
*
* @param {Array<number>} sorted a sample of one or more data points
* @returns {number} mode
* @throws {Error} if sorted is empty
* @example
* modeSorted([0, 0, 1]); // => 0
*/
function modeSorted(sorted) {
// Handle edge cases:
// The mode of an empty list is undefined
if (sorted.length === 0) {
throw new Error("mode requires at least one data point");
} else if (sorted.length === 1) {
return sorted[0];
}
// This assumes it is dealing with an array of size > 1, since size
// 0 and 1 are handled immediately. Hence it starts at index 1 in the
// array.
var last = sorted[0],
// store the mode as we find new modes
value = NaN,
// store how many times we've seen the mode
maxSeen = 0,
// how many times the current candidate for the mode
// has been seen
seenThis = 1;
// end at sorted.length + 1 to fix the case in which the mode is
// the highest number that occurs in the sequence. the last iteration
// compares sorted[i], which is undefined, to the highest number
// in the series
for (var i = 1; i < sorted.length + 1; i++) {
// we're seeing a new number pass by
if (sorted[i] !== last) {
// the last number is the new mode since we saw it more
// often than the old one
if (seenThis > maxSeen) {
maxSeen = seenThis;
value = last;
}
seenThis = 1;
last = sorted[i];
// if this isn't a new number, it's one more occurrence of
// the potential mode
} else {
seenThis++;
}
}
return value;
}
/**
* Sort an array of numbers by their numeric value, ensuring that the
* array is not changed in place.
*
* This is necessary because the default behavior of .sort
* in JavaScript is to sort arrays as string values
*
* [1, 10, 12, 102, 20].sort()
* // output
* [1, 10, 102, 12, 20]
*
* @param {Array<number>} x input array
* @return {Array<number>} sorted array
* @private
* @example
* numericSort([3, 2, 1]) // => [1, 2, 3]
*/
function numericSort(x) {
return (
x
// ensure the array is not changed in-place
.slice()
// comparator function that treats input as numeric
.sort(function (a, b) {
return a - b;
})
);
}
/**
* The [mode](https://en.wikipedia.org/wiki/Mode_%28statistics%29) is the number
* that appears in a list the highest number of times.
* There can be multiple modes in a list: in the event of a tie, this
* algorithm will return the most recently seen mode.
*
* This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency):
* a method of finding a typical or central value of a set of numbers.
*
* This runs in `O(n log(n))` because it needs to sort the array internally
* before running an `O(n)` search to find the mode.
*
* @param {Array<number>} x input
* @returns {number} mode
* @example
* mode([0, 0, 1]); // => 0
*/
function mode(x) {
// Sorting the array lets us iterate through it below and be sure
// that every time we see a new number it's new and we'll never
// see the same number twice
return modeSorted(numericSort(x));
}
/* globals Map: false */
/**
* The [mode](https://en.wikipedia.org/wiki/Mode_%28statistics%29) is the number
* that appears in a list the highest number of times.
* There can be multiple modes in a list: in the event of a tie, this
* algorithm will return the most recently seen mode.
*
* modeFast uses a Map object to keep track of the mode, instead of the approach
* used with `mode`, a sorted array. As a result, it is faster
* than `mode` and supports any data type that can be compared with `==`.
* It also requires a
* [JavaScript environment with support for Map](https://kangax.github.io/compat-table/es6/#test-Map),
* and will throw an error if Map is not available.
*
* This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency):
* a method of finding a typical or central value of a set of numbers.
*
* @param {Array<*>} x a sample of one or more data points
* @returns {?*} mode
* @throws {ReferenceError} if the JavaScript environment doesn't support Map
* @throws {Error} if x is empty
* @example
* modeFast(['rabbits', 'rabbits', 'squirrels']); // => 'rabbits'
*/
function modeFast(x) {
// This index will reflect the incidence of different values, indexing
// them like
// { value: count }
var index = new Map();
// A running `mode` and the number of times it has been encountered.
var mode;
var modeCount = 0;
for (var i = 0; i < x.length; i++) {
var newCount = index.get(x[i]);
if (newCount === undefined) {
newCount = 1;
} else {
newCount++;
}
if (newCount > modeCount) {
mode = x[i];
modeCount = newCount;
}
index.set(x[i], newCount);
}
if (modeCount === 0) {
throw new Error("mode requires at last one data point");
}
return mode;
}
/**
* The min is the lowest number in the array.
* This runs in `O(n)`, linear time, with respect to the length of the array.
*
* @param {Array<number>} x sample of one or more data points
* @throws {Error} if the length of x is less than one
* @returns {number} minimum value
* @example
* min([1, 5, -10, 100, 2]); // => -10
*/
function min(x) {
if (x.length === 0) {
throw new Error("min requires at least one data point");
}
var value = x[0];
for (var i = 1; i < x.length; i++) {
if (x[i] < value) {
value = x[i];
}
}
return value;
}
/**
* This computes the maximum number in an array.
*
* This runs in `O(n)`, linear time, with respect to the length of the array.
*
* @param {Array<number>} x sample of one or more data points
* @returns {number} maximum value
* @throws {Error} if the length of x is less than one
* @example
* max([1, 2, 3, 4]);
* // => 4
*/
function max(x) {
if (x.length === 0) {
throw new Error("max requires at least one data point");
}
var value = x[0];
for (var i = 1; i < x.length; i++) {
if (x[i] > value) {
value = x[i];
}
}
return value;
}
/**
* This computes the minimum & maximum number in an array.
*
* This runs in `O(n)`, linear time, with respect to the length of the array.
*
* @param {Array<number>} x sample of one or more data points
* @returns {Array<number>} minimum & maximum value
* @throws {Error} if the length of x is less than one
* @example
* extent([1, 2, 3, 4]);
* // => [1, 4]
*/
function extent(x) {
if (x.length === 0) {
throw new Error("extent requires at least one data point");
}
var min = x[0];
var max = x[0];
for (var i = 1; i < x.length; i++) {
if (x[i] > max) {
max = x[i];
}
if (x[i] < min) {
min = x[i];
}
}
return [min, max];
}
/**
* The minimum is the lowest number in the array. With a sorted array,
* the first element in the array is always the smallest, so this calculation
* can be done in one step, or constant time.
*
* @param {Array<number>} x input
* @returns {number} minimum value
* @example
* minSorted([-100, -10, 1, 2, 5]); // => -100
*/
function minSorted(x) {
return x[0];
}
/**
* The maximum is the highest number in the array. With a sorted array,
* the last element in the array is always the largest, so this calculation
* can be done in one step, or constant time.
*
* @param {Array<number>} x input
* @returns {number} maximum value
* @example
* maxSorted([-100, -10, 1, 2, 5]); // => 5
*/
function maxSorted(x) {
return x[x.length - 1];
}
/**
* The extent is the lowest & highest number in the array. With a sorted array,
* the first element in the array is always the lowest while the last element is always the largest, so this calculation
* can be done in one step, or constant time.
*
* @param {Array<number>} x input
* @returns {Array<number>} minimum & maximum value
* @example
* extentSorted([-100, -10, 1, 2, 5]); // => [-100, 5]
*/
function extentSorted(x) {
return [x[0], x[x.length - 1]];
}
/**
* The simple [sum](https://en.wikipedia.org/wiki/Summation) of an array
* is the result of adding all numbers together, starting from zero.
*
* This runs in `O(n)`, linear time, with respect to the length of the array.
*
* @param {Array<number>} x input
* @return {number} sum of all input numbers
* @example
* sumSimple([1, 2, 3]); // => 6
*/
function sumSimple(x) {
var value = 0;
for (var i = 0; i < x.length; i++) {
value += x[i];
}
return value;
}
/**
* The [product](https://en.wikipedia.org/wiki/Product_(mathematics)) of an array
* is the result of multiplying all numbers together, starting using one as the multiplicative identity.
*
* This runs in `O(n)`, linear time, with respect to the length of the array.
*
* @param {Array<number>} x input
* @return {number} product of all input numbers
* @example
* product([1, 2, 3, 4]); // => 24
*/
function product(x) {
var value = 1;
for (var i = 0; i < x.length; i++) {
value *= x[i];
}
return value;
}
/**
* This is the internal implementation of quantiles: when you know
* that the order is sorted, you don't need to re-sort it, and the computations
* are faster.
*
* @param {Array<number>} x sample of one or more data points
* @param {number} p desired quantile: a number between 0 to 1, inclusive
* @returns {number} quantile value
* @throws {Error} if p ix outside of the range from 0 to 1
* @throws {Error} if x is empty
* @example
* quantileSorted([3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20], 0.5); // => 9
*/
function quantileSorted(x, p) {
var idx = x.length * p;
if (x.length === 0) {
throw new Error("quantile requires at least one data point.");
} else if (p < 0 || p > 1) {
throw new Error("quantiles must be between 0 and 1");
} else if (p === 1) {
// If p is 1, directly return the last element
return x[x.length - 1];
} else if (p === 0) {
// If p is 0, directly return the first element
return x[0];
} else if (idx % 1 !== 0) {
// If p is not integer, return the next element in array
return x[Math.ceil(idx) - 1];
} else if (x.length % 2 === 0) {
// If the list has even-length, we'll take the average of this number
// and the next value, if there is one
return (x[idx - 1] + x[idx]) / 2;
} else {
// Finally, in the simple case of an integer value
// with an odd-length list, return the x value at the index.
return x[idx];
}
}
/**
* Rearrange items in `arr` so that all items in `[left, k]` range are the smallest.
* The `k`-th element will have the `(k - left + 1)`-th smallest value in `[left, right]`.
*
* Implements Floyd-Rivest selection algorithm https://en.wikipedia.org/wiki/Floyd-Rivest_algorithm
*
* @param {Array<number>} arr input array
* @param {number} k pivot index
* @param {number} [left] left index
* @param {number} [right] right index
* @returns {void} mutates input array
* @example
* var arr = [65, 28, 59, 33, 21, 56, 22, 95, 50, 12, 90, 53, 28, 77, 39];
* quickselect(arr, 8);
* // = [39, 28, 28, 33, 21, 12, 22, 50, 53, 56, 59, 65, 90, 77, 95]
*/
function quickselect(arr, k, left, right) {
left = left || 0;
right = right || arr.length - 1;
while (right > left) {
// 600 and 0.5 are arbitrary constants chosen in the original paper to minimize execution time
if (right - left > 600) {
var n = right - left + 1;
var m = k - left + 1;
var z = Math.log(n);
var s = 0.5 * Math.exp((2 * z) / 3);
var sd = 0.5 * Math.sqrt((z * s * (n - s)) / n);
if (m - n / 2 < 0) { sd *= -1; }
var newLeft = Math.max(left, Math.floor(k - (m * s) / n + sd));
var newRight = Math.min(
right,
Math.floor(k + ((n - m) * s) / n + sd)
);
quickselect(arr, k, newLeft, newRight);
}
var t = arr[k];
var i = left;
var j = right;
swap(arr, left, k);
if (arr[right] > t) { swap(arr, left, right); }
while (i < j) {
swap(arr, i, j);
i++;
j--;
while (arr[i] < t) { i++; }
while (arr[j] > t) { j--; }
}
if (arr[left] === t) { swap(arr, left, j); }
else {
j++;
swap(arr, j, right);
}
if (j <= k) { left = j + 1; }
if (k <= j) { right = j - 1; }
}
}
function swap(arr, i, j) {
var tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
/**
* The [quantile](https://en.wikipedia.org/wiki/Quantile):
* this is a population quantile, since we assume to know the entire
* dataset in this library. This is an implementation of the
* [Quantiles of a Population](http://en.wikipedia.org/wiki/Quantile#Quantiles_of_a_population)
* algorithm from wikipedia.
*
* Sample is a one-dimensional array of numbers,
* and p is either a decimal number from 0 to 1 or an array of decimal
* numbers from 0 to 1.
* In terms of a k/q quantile, p = k/q - it's just dealing with fractions or dealing
* with decimal values.
* When p is an array, the result of the function is also an array containing the appropriate
* quantiles in input order
*
* @param {Array<number>} x sample of one or more numbers
* @param {Array<number> | number} p the desired quantile, as a number between 0 and 1
* @returns {number} quantile
* @example
* quantile([3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20], 0.5); // => 9
*/
function quantile(x, p) {
var copy = x.slice();
if (Array.isArray(p)) {
// rearrange elements so that each element corresponding to a requested
// quantile is on a place it would be if the array was fully sorted
multiQuantileSelect(copy, p);
// Initialize the result array
var results = [];
// For each requested quantile
for (var i = 0; i < p.length; i++) {
results[i] = quantileSorted(copy, p[i]);
}
return results;
} else {
var idx = quantileIndex(copy.length, p);
quantileSelect(copy, idx, 0, copy.length - 1);
return quantileSorted(copy, p);
}
}
function quantileSelect(arr, k, left, right) {
if (k % 1 === 0) {
quickselect(arr, k, left, right);
} else {
k = Math.floor(k);
quickselect(arr, k, left, right);
quickselect(arr, k + 1, k + 1, right);
}
}
function multiQuantileSelect(arr, p) {
var indices = [0];
for (var i = 0; i < p.length; i++) {
indices.push(quantileIndex(arr.length, p[i]));
}
indices.push(arr.length - 1);
indices.sort(compare);
var stack = [0, indices.length - 1];
while (stack.length) {
var r = Math.ceil(stack.pop());
var l = Math.floor(stack.pop());
if (r - l <= 1) { continue; }
var m = Math.floor((l + r) / 2);
quantileSelect(
arr,
indices[m],
Math.floor(indices[l]),
Math.ceil(indices[r])
);
stack.push(l, m, m, r);
}
}
function compare(a, b) {
return a - b;
}
function quantileIndex(len, p) {
var idx = len * p;
if (p === 1) {
// If p is 1, directly return the last index
return len - 1;
} else if (p === 0) {
// If p is 0, directly return the first index
return 0;
} else if (idx % 1 !== 0) {
// If index is not integer, return the next index in array
return Math.ceil(idx) - 1;
} else if (len % 2 === 0) {
// If the list has even-length, we'll return the middle of two indices
// around quantile to indicate that we need an average value of the two
return idx - 0.5;
} else {
// Finally, in the simple case of an integer index
// with an odd-length list, return the index
return idx;
}
}
/* eslint no-bitwise: 0 */
/**
* This function returns the quantile in which one would find the given value in
* the given array. With a sorted array, leveraging binary search, we can find
* this information in logarithmic time.
*
* @param {Array<number>} x input
* @returns {number} value value
* @example
* quantileRankSorted([1, 2, 3, 4], 3); // => 0.75
* quantileRankSorted([1, 2, 3, 3, 4], 3); // => 0.7
* quantileRankSorted([1, 2, 3, 4], 6); // => 1
* quantileRankSorted([1, 2, 3, 3, 5], 4); // => 0.8
*/
function quantileRankSorted(x, value) {
// Value is lesser than any value in the array
if (value < x[0]) {
return 0;
}
// Value is greater than any value in the array
if (value > x[x.length - 1]) {
return 1;
}
var l = lowerBound(x, value);
// Value is not in the array
if (x[l] !== value) {
return l / x.length;
}
l++;
var u = upperBound(x, value);
// The value exists only once in the array
if (u === l) {
return l / x.length;
}
// Here, we are basically computing the mean of the range of indices
// containing our searched value. But, instead, of initializing an
// array and looping over it, there is a dedicated math formula that
// we apply below to get the result.
var r = u - l + 1;
var sum = (r * (u + l)) / 2;
var mean = sum / r;
return mean / x.length;
}
function lowerBound(x, value) {
var mid = 0;
var lo = 0;
var hi = x.length;
while (lo < hi) {
mid = (lo + hi) >>> 1;
if (value <= x[mid]) {
hi = mid;
} else {
lo = -~mid;
}
}
return lo;
}
function upperBound(x, value) {
var mid = 0;
var lo = 0;
var hi = x.length;
while (lo < hi) {
mid = (lo + hi) >>> 1;
if (value >= x[mid]) {
lo = -~mid;
} else {
hi = mid;
}
}
return lo;
}
/**
* This function returns the quantile in which one would find the given value in
* the given array. It will copy and sort your array before each run, so
* if you know your array is already sorted, you should use `quantileRankSorted`
* instead.
*
* @param {Array<number>} x input
* @returns {number} value value
* @example
* quantileRank([4, 3, 1, 2], 3); // => 0.75
* quantileRank([4, 3, 2, 3, 1], 3); // => 0.7
* quantileRank([2, 4, 1, 3], 6); // => 1
* quantileRank([5, 3, 1, 2, 3], 4); // => 0.8
*/
function quantileRank(x, value) {
// Cloning and sorting the array
var sortedCopy = numericSort(x);
return quantileRankSorted(sortedCopy, value);
}
/**
* The [Interquartile range](http://en.wikipedia.org/wiki/Interquartile_range) is
* a measure of statistical dispersion, or how scattered, spread, or
* concentrated a distribution is. It's computed as the difference between
* the third quartile and first quartile.
*
* @param {Array<number>} x sample of one or more numbers
* @returns {number} interquartile range: the span between lower and upper quartile,
* 0.25 and 0.75
* @example
* interquartileRange([0, 1, 2, 3]); // => 2
*/
function interquartileRange(x) {
// Interquartile range is the span between the upper quartile,
// at `0.75`, and lower quartile, `0.25`
var q1 = quantile(x, 0.75);
var q2 = quantile(x, 0.25);
if (typeof q1 === "number" && typeof q2 === "number") {
return q1 - q2;
}
}