/
stats.gleam
1686 lines (1657 loc) · 44.6 KB
/
stats.gleam
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
////<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.15.6/dist/katex.min.css" integrity="sha384-ZPe7yZ91iWxYumsBEOn7ieg8q/o+qh/hQpSaPow8T6BwALcXSCS6C6fSRPIAnTQs" crossorigin="anonymous">
////<script defer src="https://cdn.jsdelivr.net/npm/katex@0.15.6/dist/katex.min.js" integrity="sha384-ljao5I1l+8KYFXG7LNEA7DyaFvuvSCmedUf6Y6JI7LJqiu8q5dEivP2nDdFH31V4" crossorigin="anonymous"></script>
////<script defer src="https://cdn.jsdelivr.net/npm/katex@0.15.6/dist/contrib/auto-render.min.js" integrity="sha384-+XBljXPPiv+OzfbB3cVmLHf4hdUFHlWNZN5spNQ7rmHTXpd7WvJum6fIACpNNfIR" crossorigin="anonymous"></script>
////<script>
//// document.addEventListener("DOMContentLoaded", function() {
//// renderMathInElement(document.body, {
//// // customised options
//// // • auto-render specific keys, e.g.:
//// delimiters: [
//// {left: '$$', right: '$$', display: false},
//// // {left: '$', right: '$', display: false},
//// // {left: '\\(', right: '\\)', display: false},
//// {left: '\\[', right: '\\]', display: true}
//// ],
//// // • rendering keys, e.g.:
//// throwOnError : false
//// });
//// });
////</script>
////<style>
//// .katex { font-size: 1.1em; }
////</style>
////
//// A module containing several helpful functions for computing and working with statistics.
////
//// ---
////
//// * **Types**
//// * [`Bin`](#Bin)
//// * [`Range`](#Range)
//// * **Statistical functions**
//// * [`freedman_diaconis_rule`](#freedman_diaconis_rule)
//// * [`correlation`](#correlation)
//// * [`gmean`](#gmean)
//// * [`histogram`](#histogram)
//// * [`hmean`](#hmean)
//// * [`iqr`](#iqr)
//// * [`kurtosis`](#kurtosis)
//// * [`mean`](#mean)
//// * [`median`](#median)
//// * [`moment`](#moment)
//// * [`percentile`](#percentile)
//// * [`skewness`](#skewness)
//// * [`std`](#std)
//// * [`var`](#var)
//// * [`zscore`](#zscore)
//// * **Miscellaneous functions**
//// * [`allclose`](#allclose)
//// * [`amax`](#amax)
//// * [`amin`](#amin)
//// * [`argmax`](#argmax)
//// * [`argmin`](#argmin)
//// * [`isclose`](#isclose)
//// * [`sum`](#sum)
//// * [`trim`](#trim)
import gleam/list
import gleam/int
import gleam/float
import gleam/pair
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// A type used to represent a min/max interval. The `Range` type is among
/// others used to represent the bin boundaries in a histogram.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleam_stats/stats
/// import gleeunit/should
///
/// pub fn example () {
/// // Create a range
/// let range = stats.Range(0., 1.)
/// // Retrieve min and max values
/// let stats.Range(min, max) = range
/// min
/// |> should.equal(0.)
/// max
/// |> should.equal(1.)
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub type Range {
Range(min: Float, max: Float)
}
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// A type used to represent the bins in a histogram. The type is an alias
/// of a tuple containing a min/max range and a count of the values in
/// that range.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleeunit/should
/// import gleam/pair
/// import gleam_stats/stats
///
/// pub fn example () {
/// // Create a bin
/// let bin: stats.Bin = #(stats.Range(0., 1.), 999)
/// // Retrieve min and max values
/// let stats.Range(min, max) = pair.first(bin)
/// min
/// |> should.equal(0.)
/// max
/// |> should.equal(1.)
/// // Retrieve count
/// let count = pair.second(bin)
/// count
/// |> should.equal(999)
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub type Bin =
#(Range, Int)
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// Use Freedman-Diaconis’s Rule to determine the bin widths of a
/// histogram.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleeunit/should
/// import gleam_stats/stats
///
/// pub fn example () {
/// // An empty list returns an error
/// []
/// |> stats.freedman_diaconis_rule()
/// |> should.be_error()
///
/// // Calculate histogram bin widths
/// list.range(0, 1000)
/// |> list.map(fn(x: Int) -> Float { int.to_float(x) })
/// |> stats.freedman_diaconis_rule()
/// |> should.equal(Ok(10.))
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub fn freedman_diaconis_rule(arr: List(Float)) -> Result(Float, String) {
case arr {
[] ->
"Invalid input argument: The list is empty."
|> Error
_ -> {
let length: Float = int.to_float(list.length(arr))
assert Ok(iqr) =
arr
|> iqr()
assert Ok(lower) =
arr
|> amin()
assert Ok(upper) =
arr
|> amax()
let width: Float = 2. *. iqr /. float.power(length, 1. /. 3.)
case width <. { upper -. lower } /. length {
// If the bin size/width is too small then return an error.
// The bin size/width should be set manually or in some other
// way.
True ->
"The determined bin width is too small. Determine the width manually or in another way."
|> Error
False ->
float.ceiling({ upper -. lower } /. width)
|> Ok
}
}
}
}
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// Calculate Pearson's sample correlation coefficient to determine the linear
/// relationship between the elements in two lists of equal
/// length. The correlation coefficient $$r_{xy} \in \[-1, 1\]$$ is calculated
/// as:
///
/// \\[
/// r_{xy} =\frac{\sum ^n _{i=1}(x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum^n _{i=1}(x_i - \bar{x})^2} \sqrt{\sum^n _{i=1}(y_i - \bar{y})^2}}
/// \\]
///
/// In the formula, $$n$$ is the sample size (the length of the input lists),
/// $$x_i$$, $$y_i$$ are the corresponding sample points indexed by $$i$$ and
/// $$\bar{x}$$, $$\bar{y}$$ are the sample means.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleeunit/should
/// import gleam_stats/stats
///
/// pub fn example () {
/// // An empty lists returns an error
/// stats.correlation([], [])
/// |> should.be_error()
///
/// // Lists with fewer than 2 elements return an error
/// stats.correlation([1.0], [1.0])
/// |> should.be_error()
///
/// // Lists of uneqal length return an error
/// stats.correlation([1.0, 2.0, 3.0], [1.0, 2.0])
/// |> should.be_error()
///
/// // Perfect positive correlation
/// let xarr0: List(Float) =
/// list.range(0, 100)
/// |> list.map(fn(x: Int) -> Float { int.to_float(x) })
/// let yarr0: List(Float) =
/// list.range(0, 100)
/// |> list.map(fn(x: Int) -> Float { int.to_float(x) })
/// stats.correlation(xarr0, yarr0)
/// |> should.equal(Ok(1.))
///
/// // Perfect negative correlation
/// let xarr0: List(Float) =
/// list.range(0, 100)
/// |> list.map(fn(x: Int) -> Float { -1. *. int.to_float(x) })
/// let yarr0: List(Float) =
/// list.range(0, 100)
/// |> list.map(fn(x: Int) -> Float { int.to_float(x) })
/// stats.correlation(xarr0, yarr0)
/// |> should.equal(Ok(-1.))
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub fn correlation(
xarr: List(Float),
yarr: List(Float),
) -> Result(Float, String) {
let xlen: Int = list.length(xarr)
let ylen: Int = list.length(yarr)
case xlen <= 0, ylen <= 0 {
True, True ->
"Invlaid input argument: length(xarr) == 0 or length(yarr) == 0. Valid input is length(xarr) > 0 and length(yarr) > 0."
|> Error
_, _ ->
case xlen == ylen {
False ->
"Invalid input argument: length(xarr) != length(yarr). Valid input is when length(xarr) == length(yarr)."
|> Error
True ->
case xlen >= 2 && ylen >= 2 {
False ->
"Invalid input argument: length(xarr) < 2 or length(yarr) < 2. Valid input is when length(xarr) >= 2 and length(yarr) >= 2."
|> Error
True -> {
assert Ok(xmean) =
xarr
|> mean()
assert Ok(ymean) =
yarr
|> mean()
let a: Float =
list.zip(xarr, yarr)
|> list.map(fn(z: #(Float, Float)) -> Float {
{ pair.first(z) -. xmean } *. { pair.second(z) -. ymean }
})
|> sum()
let b: Float =
xarr
|> list.map(fn(x: Float) { { x -. xmean } *. { x -. xmean } })
|> sum()
let c: Float =
yarr
|> list.map(fn(y: Float) { { y -. ymean } *. { y -. ymean } })
|> sum()
// The argument is the product of two sums of squared differences
// it will never be negative. So extract it directly:
assert Ok(val0) = float.square_root(b *. c)
a /. val0
|> Ok
}
}
}
}
}
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// Calculcate the geometric mean $$\bar{x}$$ of the elements in a list:
///
/// \\[
/// \bar{x} = \left(\prod^{n}_{i=1} x_i\right)^{\frac{1}{n}}
/// \\]
///
/// In the formula, $$n$$ is the sample size (the length of the list) and
/// $$x_i$$ is the sample point in the input list indexed by $$i$$.
/// Note: The geometric mean is only defined for positive numbers.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleeunit/should
/// import gleam_stats/stats
///
/// pub fn example () {
/// // An empty list returns an error
/// []
/// |> stats.gmean()
/// |> should.be_error()
///
/// // List with negative numbers returns an error
/// [-1., -3., -6.]
/// |> stats.gmean()
/// |> should.be_error()
///
/// // Valid input returns a result
/// [1., 3., 9.]
/// |> stats.gmean()
/// |> should.equal(Ok(3.))
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub fn gmean(arr: List(Float)) -> Result(Float, String) {
case arr {
[] ->
"Invalid input argument: The list is empty."
|> Error
_ -> {
let xval: Result(Float, String) =
arr
|> list.try_fold(
1.,
fn(acc: Float, a: Float) -> Result(Float, String) {
case a >=. 0. {
True ->
acc *. a
|> Ok
False ->
"The geometric mean is only defined for positive numbers."
|> Error
}
},
)
case xval {
Error(string) ->
string
|> Error
Ok(xval) ->
xval
|> fn(x: Float) {
float.power(x, 1. /. int.to_float(list.length(arr)))
}
|> Ok
}
}
}
}
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// Create a histogram of the elements in a list.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleam_stats/stats
/// import gleeunit/should
///
/// pub fn example () {
/// // An empty lists returns an error
/// []
/// |> stats.histogram(1.)
/// |> should.be_error()
///
/// // Create the bins of a histogram given a list of values
/// list.range(0, 100)
/// |> list.map(fn(x: Int) -> Float { int.to_float(x) })
/// // Below 25. is the bin width
/// // The Freedman-Diaconis’s Rule can be used to determine a decent value
/// |> stats.histogram(25.)
/// |> should.equal(Ok([
/// #(stats.Range(0., 25.), 25),
/// #(stats.Range(25., 50.), 25),
/// #(stats.Range(50., 75.), 25),
/// #(stats.Range(75., 100.), 25),
/// ]))
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub fn histogram(arr: List(Float), width: Float) -> Result(List(Bin), String) {
case arr {
[] ->
"Invalid input argument: The list is empty."
|> Error
_ ->
case create_bins(arr, width) {
Error(string) ->
string
|> Error
Ok(bins) ->
bins
|> bin_elements(arr)
|> Ok
}
}
}
fn create_bins(arr: List(Float), width: Float) -> Result(List(Bin), String) {
case arr {
[] ->
"Invalid input argument: The list is empty."
|> Error
_ ->
case width <. 0.0 {
True ->
"Invalid input argument: width < 0. Valid input is width > 0."
|> Error
False -> {
assert Ok(min) =
arr
|> amin()
assert Ok(max) =
arr
|> amax()
let inc: Float =
{ 1.001 *. max -. 0.999 *. min } /. width
|> float.ceiling()
list.range(0, float.round(inc))
|> list.map(fn(x: Int) -> Bin {
#(Range(width *. int.to_float(x), width *. int.to_float(x + 1)), 0)
})
|> Ok
}
}
}
}
fn find_bin(bins: List(Bin), key: Float) -> Result(Bin, Nil) {
bins
|> list.find(fn(b: Bin) -> Bool {
let Range(cmin, cmax) = pair.first(b)
key >=. cmin && key <. cmax
})
}
fn bin_elements(bins: List(Bin), arr: List(Float)) -> List(Bin) {
arr
|> list.fold(
bins,
fn(acc: List(Bin), key: Float) -> List(Bin) {
// If the bins were constructed correctly then there should be a bin that fits
// every value in the input array
assert Ok(bin) =
acc
|> find_bin(key)
// Retrieve key-value pair
assert Ok(kv) = list.key_pop(acc, pair.first(bin))
// Update and set key-value pair
list.key_set(pair.second(kv), pair.first(bin), pair.first(kv) + 1)
},
)
}
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// Calculcate the harmonic mean $$\bar{x}$$ of the elements in a list:
///
/// \\[
/// \bar{x} = \frac{n}{\sum_{i=1}^{n}\frac{1}{x_i}}
/// \\]
///
/// In the formula, $$n$$ is the sample size (the length of the list) and
/// $$x_i$$ is the sample point in the input list indexed by $$i$$.
/// Note: The harmonic mean is only defined for positive numbers.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleeunit/should
/// import gleam_stats/stats
///
/// pub fn example () {
/// // An empty list returns an error
/// []
/// |> stats.hmean()
/// |> should.be_error()
///
/// // List with negative numbers returns an error
/// [-1., -3., -6.]
/// |> stats.hmean()
/// |> should.be_error()
///
/// // Valid input returns a result
/// [1., 3., 6.]
/// |> stats.hmean()
/// |> should.equal(Ok(2.))
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub fn hmean(arr: List(Float)) -> Result(Float, String) {
case arr {
[] ->
"Invalid input argument: The list is empty."
|> Error
_ -> {
let xarr: Result(List(Float), String) =
arr
|> list.try_map(fn(a: Float) -> Result(Float, String) {
case a >=. 0. {
True ->
1. /. a
|> Ok
False ->
"The harmonic mean is only defined for positive numbers."
|> Error
}
})
case xarr {
Error(string) ->
string
|> Error
Ok(xarr) ->
xarr
|> sum()
|> fn(x: Float) { int.to_float(list.length(xarr)) /. x }
|> Ok
}
}
}
}
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// Calculate the interquartile range (IQR) of the elements in a list.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleeunit/should
/// import gleam_stats/stats
///
/// pub fn example () {
/// // An empty list returns an error
/// []
/// |> stats.iqr()
/// |> should.be_error()
///
/// // Valid input returns a result
/// [1., 2., 3., 4., 5.]
/// |> stats.iqr()
/// |> should.equal(Ok(3.))
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub fn iqr(arr: List(Float)) -> Result(Float, String) {
case arr {
[] ->
"Invalid input argument: The list is empty."
|> Error
_ -> {
let length: Int = list.length(arr)
case int.is_even(length) {
True -> {
// x contains the n smallest values
// y contains the n largest values
let #(x, y) =
arr
|> list.split(length / 2)
assert Ok(val0) = median(y)
assert Ok(val1) = median(x)
val0 -. val1
|> Ok
}
False -> {
// x contains the n smallest values
let #(x, _z) =
arr
|> list.split({ length - 1 } / 2)
// y contains the n largest values
let #(_z, y) =
arr
|> list.split({ length + 1 } / 2)
assert Ok(val0) = median(y)
assert Ok(val1) = median(x)
val0 -. val1
|> Ok
}
}
}
}
}
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// Calculcate the sample kurtosis of a list of elements using the
/// definition of Fisher.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleeunit/should
/// import gleam_stats/stats
///
/// pub fn example () {
/// // An empty list returns an error
/// []
/// |> stats.skewness()
/// |> should.be_error()
///
/// // No tail
/// // -> Fisher's definition gives kurtosis -3
/// [1., 1., 1., 1.]
/// |> stats.kurtosis()
/// |> should.equal(Ok(-3.))
///
/// // Distribution with a tail
/// // -> Higher kurtosis
/// [1., 1., 1., 2.]
/// |> stats.kurtosis()
/// |> fn(x: Result(Float, String)) -> Bool {
/// case x {
/// Ok(x) -> x >. -3.
/// _ -> False
/// }
/// }
/// |> should.be_true()
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub fn kurtosis(arr: List(Float)) -> Result(Float, String) {
case arr {
[] ->
"Invalid input argument: The list is empty."
|> Error
_ -> {
assert Ok(m2) = moment(arr, 2)
assert Ok(m4) = moment(arr, 4)
m4 /. float.power(m2, 2.0) -. 3.
|> Ok
}
}
}
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// Calculcate the arithmetic mean of the elements in a list:
///
/// \\[
/// \bar{x} = \frac{1}{n}\sum_{i=1}^n x_i
/// \\]
///
/// In the formula, $$n$$ is the sample size (the length of the list) and
/// $$x_i$$ is the sample point in the input list indexed by $$i$$.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleeunit/should
/// import gleam_stats/stats
///
/// pub fn example () {
/// // An empty list returns an error
/// []
/// |> stats.mean()
/// |> should.be_error()
///
/// // Valid input returns a result
/// [1., 2., 3.]
/// |> stats.mean()
/// |> should.equal(Ok(2.))
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub fn mean(arr: List(Float)) -> Result(Float, String) {
case arr {
[] ->
"Invalid input argument: The list is empty."
|> Error
_ ->
arr
|> sum()
|> fn(a: Float) -> Float { a /. int.to_float(list.length(arr)) }
|> Ok
}
}
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// Calculcate the median of the elements in a list.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleeunit/should
/// import gleam_stats/stats
///
/// pub fn example () {
/// // An empty list returns an error
/// []
/// |> stats.median()
/// |> should.be_error()
///
/// // Valid input returns a result
/// [1., 2., 3.]
/// |> stats.median()
/// |> should.equal(Ok(2.))
///
/// [1., 2., 3., 4.]
/// |> stats.median()
/// |> should.equal(Ok(2.5))
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub fn median(arr: List(Float)) -> Result(Float, String) {
case arr {
[] ->
"Invalid input argument: The list is empty."
|> Error
_ -> {
let count: Int = list.length(arr)
let mid: Int = list.length(arr) / 2
let sorted: List(Float) = list.sort(arr, float.compare)
case int.is_odd(count) {
// If there is an odd number of elements in the list, then the median
// is just the middle value
True -> {
assert Ok(val0) = list.at(sorted, mid)
val0
|> Ok
}
// If there is an even number of elements in the list, then the median
// is the mean of the two middle values
False -> {
assert Ok(val0) = list.at(sorted, mid - 1)
assert Ok(val1) = list.at(sorted, mid)
[val0, val1]
|> mean()
}
}
}
}
}
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// Calculcate the n'th moment about the mean of a list of elements.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleeunit/should
/// import gleam_stats/stats
///
/// pub fn example () {
/// // An empty list returns an error
/// []
/// |> stats.moment(0)
/// |> should.be_error()
///
/// // 0th moment about the mean is 1. per definition
/// [0., 1., 2., 3., 4.]
/// |> stats.moment(0)
/// |> should.equal(Ok(1.))
///
/// // 1st moment about the mean is 0. per definition
/// [0., 1., 2., 3., 4.]
/// |> stats.moment(1)
/// |> should.equal(Ok(0.))
///
/// // 2nd moment about the mean
/// [0., 1., 2., 3., 4.]
/// |> stats.moment(2)
/// |> should.equal(Ok(2.))
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub fn moment(arr: List(Float), n: Int) -> Result(Float, String) {
case arr {
[] ->
"Invalid input argument: The list is empty."
|> Error
_ ->
case n >= 0 {
True ->
case n {
// 0th moment about the mean is 1.0 by definition
0 ->
1.0
|> Ok
// 1st moment about the mean is 0.0 by definition
1 ->
0.0
|> Ok
// n'th moment about the mean
_ -> {
assert Ok(m1) = mean(arr)
arr
|> list.map(fn(a: Float) { float.power(a -. m1, int.to_float(n)) })
|> mean()
}
}
False ->
"Invalid input argument: n < 0. Valid input is n > 0."
|> Error
}
}
}
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// Calculate the n'th percentile of the elements in a list using
/// linear interpolation between closest ranks.
///
/// <details>
/// <summary>Example:</summary>
///
/// import gleeunit/should
/// import gleam_stats/stats
///
/// pub fn example () {
/// // An empty list returns an error
/// []
/// |> stats.percentile(40)
/// |> should.be_error()
///
/// // Calculate 40th percentile
/// [15., 20., 35., 40., 50.]
/// |> stats.percentile(40)
/// |> should.equal(Ok(29.))
/// }
/// </details>
///
/// <div style="text-align: right;">
/// <a href="#">
/// <small>Back to top ↑</small>
/// </a>
/// </div>
///
pub fn percentile(arr: List(Float), n: Int) -> Result(Float, String) {
case arr {
[] ->
"Invalid input argument: The list is empty."
|> Error
_ ->
case n < 0 || n > 100 {
True ->
"Invalid input argument: n < 0 or n > 100. Valid input is 0 <= n <= 100."
|> Error
False -> {
let s: List(Float) = list.sort(arr, float.compare)
// Calculate the rank of the n'th percentile
let r: Float =
int.to_float(n) /. 100.0 *. int.to_float(list.length(arr) - 1)
let f: Int = float.truncate(r)
// Directly extract the lower and upper values. Theoretically an error
// value will not be returned as the largest index in the array that is
// accessed will be the length of the array - 1 (last element).
assert Ok(lower) = list.at(s, f)
assert Ok(upper) = list.at(s, f + 1)
lower +. { upper -. lower } *. { r -. int.to_float(f) }
|> Ok
}
}
}
}
/// <div style="text-align: right;">
/// <a href="https://github.com/nicklasxyz/gleam_stats/issues">
/// <small>Spot a typo? Open an issue!</small>
/// </a>
/// </div>
///
/// Calculcate the sample skewness of a list of elements using the
/// Fisher-Pearson coefficient of skewness.
///
/// <details>
/// <summary>Example:</summary>