-
Notifications
You must be signed in to change notification settings - Fork 62
/
SigmaDistrib.swift
1537 lines (1053 loc) · 39.7 KB
/
SigmaDistrib.swift
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
//
// Statistics library written in Swift.
//
// https://github.com/evgenyneu/SigmaSwiftStatistics
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// StandardErrorOfTheMean.swift
//
// ----------------------------
//
// Created by Alan James Salmoni on 18/12/2016.
// Copyright © 2016 Thought Into Design Ltd. All rights reserved.
//
import Foundation
public extension Sigma {
/**
Computes standard error of the mean.
http://en.wikipedia.org/wiki/Standard_error
- parameter values: Array of decimal numbers.
- returns: Standard error of the mean. Returns nil when the array is empty or contains a single value.
Formula:
SE = s / sqrt(n)
Where:
s is the sample standard deviation.
n is the sample size.
Example:
Sigma.standardErrorOfTheMean([1, 12, 19.5, -5, 3, 8]) // 3.5412254627
*/
static func standardErrorOfTheMean(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count == 0 { return nil }
guard let stdev = standardDeviationSample(values) else { return nil }
return stdev / sqrt(count)
}
}
// ----------------------------
//
// Kurtosis.swift
//
// ----------------------------
//
// Created by Alan James Salmoni on 19/12/2016.
// Copyright © 2016 Thought Into Design Ltd. All rights reserved.
//
import Foundation
public extension Sigma {
/**
Computes kurtosis of a series of numbers. This implementation is the same as the SKEW function in Excel and Google Docs Sheets.
https://en.wikipedia.org/wiki/Kurtosis
- parameter values: Array of decimal numbers.
- returns: Kurtosis. Returns nil if the dataset contains less than 4 values. Returns nil if all the values in the dataset are the same.
Formula (LaTeX):
rac{n(n + 1)}{(n - 1)(n - 2)(n - 3)}\sum_{i=1}^{n} \Bigg( rac{x_i - ar{x}}{s} \Bigg)^4 - rac{3(n - 1)^2}{(n - 2)(n - 3)}
Example:
Sigma.kurtosisA([2, 1, 3, 4.1, 19, 1.5]) // 5.4570693277
*/
static func kurtosisA(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count < 4 { return nil }
guard let averageVal = average(values) else { return nil }
guard let stdev = standardDeviationSample(values) else { return nil }
var result = values.reduce(0.0) { sum, value in
let value = (value - averageVal) / stdev
return sum + pow(value, 4)
}
result *= (count * (count + 1) / ((count - 1) * (count - 2) * (count - 3)))
result -= 3 * pow(count - 1, 2) / ((count - 2) * (count - 3))
return result
}
/**
Computes kurtosis of a series of numbers. This implementation is the same as in Wolfram Alpha and "moments" R package.
https://en.wikipedia.org/wiki/Kurtosis
- parameter values: Array of decimal numbers.
- returns: Kurtosis. Returns nil if the dataset contains less than 2 values. Returns nil if all the values in the dataset are the same.
Formula (LaTeX):
rac{\mu_4}{\mu^2_2}
Example:
Sigma.kurtosisB([2, 1, 3, 4.1, 19, 1.5]) // 4.0138523409
*/
static func kurtosisB(_ values: [Double]) -> Double? {
if values.isEmpty { return nil }
guard let moment4 = centralMoment(values, order: 4) else { return nil }
guard let moment2 = centralMoment(values, order: 2) else { return nil }
if moment2 == 0 { return nil }
return (moment4 / pow(moment2, 2))
}
}
// ----------------------------
//
// Rank.swift
//
// ----------------------------
//
// Ranks.swift
// SigmaSwiftStatistics
//
// Created by Alan James Salmoni on 21/01/2017.
// Copyright © 2017 Evgenii Neumerzhitckii. All rights reserved.
//
import Foundation
public extension Sigma {
/// Determines how the ranks for the equal values ('ties') are calculated.
enum RankTieMethod {
/**
Calculates the average rank:
Sigma.average([100, 100, 100, 100], ties: .average) // [2.5, 2.5, 2.5, 2.5]
*/
case average
/**
Uses the mininum rank:
Sigma.rank([100, 100, 100, 100], ties: .min) // [1, 1, 1, 1]
*/
case min
/**
Uses the maximum rank:
Sigma.rank([100, 100, 100, 100], ties: .max) // [4, 4, 4, 4]
*/
case max
/**
Ranks are incremented:
Sigma.rank([100, 100, 100, 100], ties: .first) // [1, 2, 3, 4]
*/
case first
/**
Ranks are decremented:
Sigma.rank([100, 100, 100, 100], ties: .last) // [4, 3, 2, 1]
*/
case last
}
/**
Returns the ranks of the values in the array.
- parameter values: Array of decimal numbers.
- parameter ties: determines how the ranks for the equal values ('ties') are calculated. Default: .average.
- returns: Returns the ranks of the values in the array.
Examples:
Sigma.rank([2, 3, 6, 5, 3]) // [1.0, 2.5, 5.0, 4.0, 2.5]
*/
static func rank(_ values: [Double], ties: RankTieMethod = .average) -> [Double] {
var rank: Double
let start = 1.0
switch ties {
case .average:
rank = start - 0.5
default:
rank = start - 1.0
}
var increment: Double
var tinyIncrement: Double
let frequencies = Sigma.frequencies(values)
var ranks = [Double](repeating: 0, count: values.count)
for value in frequencies.keys.sorted() {
increment = Double(frequencies[value] ?? 1)
tinyIncrement = 1.0
for index in 0...(values.count - 1) {
if value == values[index] {
switch ties {
case .average:
ranks[index] = rank + (increment / 2.0)
case .min:
ranks[index] = rank + 1
case .max:
ranks[index] = rank + increment
case .first:
ranks[index] = rank + tinyIncrement
tinyIncrement += 1
case .last:
ranks[index] = rank + increment - tinyIncrement + 1.0
tinyIncrement += 1
}
}
}
rank += increment
}
return ranks
}
}
// ----------------------------
//
// Quantiles.swift
//
// ----------------------------
//
// Created by Alan James Salmoni on 21/12/2016.
// Copyright © 2016 Thought Into Design Ltd. All rights reserved.
//
import Foundation
public extension Sigma {
/**
The class contains nine functions that calculate sample quantiles corresponding to the given probability. The implementation is the same as in R. This is an implementation of the algorithms described in the Hyndman and Fan paper, 1996:
https://www.jstor.org/stable/2684934
https://www.amherst.edu/media/view/129116/original/Sample+Quantiles.pdf
The documentation of the functions is based on R and Wikipedia:
https://en.wikipedia.org/wiki/Quantile
http://stat.ethz.ch/R-manual/R-devel/library/stats/html/quantile.html
*/
static let quantiles = SigmaQuantiles()
}
public class SigmaQuantiles {
/*
This method calculates quantiles using the inverse of the empirical distribution function.
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method1(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let k = Int((probability * count))
let g = (probability * count) - Double(k)
var new_probability = 1.0
if g == 0.0 { new_probability = 0.0 }
return qDef(data, k: k, probability: new_probability)
}
/**
This method uses inverted empirical distribution function with averaging.
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method2(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let k = Int(probability * count)
let g = (probability * count) - Double(k)
var new_probability = 1.0
if g == 0.0 { new_probability = 0.5 }
return qDef(data, k: k, probability: new_probability)
}
/**
The 3rd sample quantile method from Hyndman and Fan paper (1996).
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method3(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = -0.5
let k = Int((probability * count) + m)
let g = (probability * count) + m - Double(k)
var new_probability = 1.0
if g <= 0 && k % 2 == 0 { new_probability = 0.0 }
return qDef(data, k: k, probability: new_probability)
}
/**
It uses linear interpolation of the empirical distribution function.
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method4(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = 0.0
let k = Int((probability * count) + m)
let probability = (probability * count) + m - Double(k)
return qDef(data, k: k, probability: probability)
}
/**
This method uses a piecewise linear function where the knots are the values midway through the steps of the empirical distribution function.
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method5(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = 0.5
let k = Int((probability * count) + m)
let probability = (probability * count) + m - Double(k)
return qDef(data, k: k, probability: probability)
}
/**
This method is implemented in Microsoft Excel (PERCENTILE.EXC), Minitab and SPSS. It uses linear interpolation of the expectations for the order statistics for the uniform distribution on [0,1].
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method6(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = probability
let k = Int((probability * count) + m)
let probability = (probability * count) + m - Double(k)
return qDef(data, k: k, probability: probability)
}
/**
This method is implemented in S, Microsoft Excel (PERCENTILE or PERCENTILE.INC) and Google Docs Sheets (PERCENTILE). It uses linear interpolation of the modes for the order statistics for the uniform distribution on [0, 1].
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method7(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = 1.0 - probability
let k = Int((probability * count) + m)
let probability = (probability * count) + m - Double(k)
return qDef(data, k: k, probability: probability)
}
/**
The quantiles returned by the method are approximately median-unbiased regardless of the distribution of x.
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method8(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = (probability + 1.0) / 3.0
let k = Int((probability * count) + m)
let probability = (probability * count) + m - Double(k)
return qDef(data, k: k, probability: probability)
}
/**
The quantiles returned by this method are approximately unbiased for the expected order statistics if x is normally distributed.
- parameter data: Array of decimal numbers.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
public func method9(_ data: [Double], probability: Double) -> Double? {
if probability < 0 || probability > 1 { return nil }
let data = data.sorted(by: <)
let count = Double(data.count)
let m = (0.25 * probability) + (3.0 / 8.0)
let k = Int((probability * count) + m)
let probability = (probability * count) + m - Double(k)
return qDef(data, k: k, probability: probability)
}
/**
Shared function for all quantile methods.
- parameter data: Array of decimal numbers.
- parameter k: the position of the element in the dataset.
- parameter probability: the probability value between 0 and 1, inclusive.
- returns: sample quantile.
*/
private func qDef(_ data: [Double], k: Int, probability: Double) -> Double? {
if data.isEmpty { return nil }
if k < 1 { return data[0] }
if k >= data.count { return data.last }
return ((1.0 - probability) * data[k - 1]) + (probability * data[k])
}
}
// ----------------------------
//
// StandardDeviation.swift
//
// ----------------------------
import Foundation
public extension Sigma {
/**
Computes standard deviation based on a sample.
http://en.wikipedia.org/wiki/Standard_deviation
- parameter values: Array of decimal numbers.
- returns: Standard deviation of a sample. Returns nil when the array is empty or contains a single value.
Formula:
s = sqrt( Σ( (x - m)^2 ) / (n - 1) )
Where:
m is the sample mean.
n is the sample size.
Example:
Sigma.standardDeviationSample([1, 12, 19.5, -5, 3, 8]) // 8.674195447801869
*/
static func standardDeviationSample(_ values: [Double]) -> Double? {
if let varianceSample = varianceSample(values) {
return sqrt(varianceSample)
}
return nil
}
/**
Computes standard deviation of entire population.
http://en.wikipedia.org/wiki/Standard_deviation
- parameter values: Array of decimal numbers.
- returns: Standard deviation of entire population. Returns nil for an empty array.
Formula:
σ = sqrt( Σ( (x - m)^2 ) / n )
Where:
m is the population mean.
n is the population size.
Example:
Sigma.standardDeviationPopulation([1, 12, 19.5, -5, 3, 8]) // 8.67419544780187
*/
static func standardDeviationPopulation(_ values: [Double]) -> Double? {
if let variancePopulation = variancePopulation(values) {
return sqrt(variancePopulation)
}
return nil
}
}
// ----------------------------
//
// Normal.swift
//
// ----------------------------
import Foundation
public extension Sigma {
/**
Returns the normal distribution for the given values of x, μ and σ. The returned value is the area under the normal curve to the left of the value x.
https://en.wikipedia.org/wiki/Normal_distribution
- parameter x: The input value.
- parameter μ: The mean. Default: 0.
- parameter σ: The standard deviation. Default: 1.
- returns: The value of the normal distribution. The returned value is the area under the normal curve to the left of the value x. Returns nil if σ is zero or negative.
Example:
Sigma.normalDistribution(x: -1, μ: 0, σ: 1) // 0.1586552539314570
*/
static func normalDistribution(x: Double, μ: Double = 0, σ: Double = 1) -> Double? {
if σ <= 0 { return nil }
let z = (x - μ) / σ
return 0.5 * erfc(-z * 0.5.squareRoot())
}
/**
Returns the value of the normal density function.
https://en.wikipedia.org/wiki/Normal_distribution
- parameter x: The input value of the normal density function.
- parameter μ: The mean. Default: 0.
- parameter σ: The standard deviation. Default: 1.
- returns: The value of the normal density function. Returns nil if σ is zero or negative.
Formula (LaTeX):
rac{1}{\sqrt{2 \sigma^2 \pi}} e^{ - rac{(x - \mu)^2}{2 \sigma^2} }
Where:
x is the input value of the normal density function.
μ is the mean.
σ is the standard deviation.
Example:
Sigma.normalDensity(x: 0, μ: 0, σ: 1) // 0.3989422804014327
*/
static func normalDensity(x: Double, μ: Double = 0, σ: Double = 1) -> Double? {
if σ <= 0 { return nil }
return (1 / sqrt(2 * pow(σ,2) * Double.pi)) * pow(M_E, (-( pow(x - μ, 2) / (2 * pow(σ, 2)) )))
}
/**
Returns the quantile function for the normal distribution.
https://en.wikipedia.org/wiki/Normal_distribution
- parameter p: The probability (area under the normal curve to the left of the returned value).
- parameter μ: The mean. Default: 0.
- parameter σ: The standard deviation. Default: 1.
- returns: The quantile function for the normal distribution. Returns nil if σ is zero or negative. Returns nil if p is negative or greater than one. Returns (-Double.infinity) if p is zero. Returns Double.infinity if p is one.
Example:
Sigma.normalQuantile(p: 0.025, μ: 0, σ: 1) // -1.9599639845400538
*/
static func normalQuantile(p: Double, μ: Double = 0, σ: Double = 1) -> Double? {
return qnorm(p: p, mu: μ, sigma: σ)
}
// MARK: - Protected functionality
/*
*
* Mathlib : A C Library of Special Functions
* Copyright (C) 1998 Ross Ihaka
* Copyright (C) 2000--2005 The R Core Team
* based on AS 111 (C) 1977 Royal Statistical Society
* and on AS 241 (C) 1988 Royal Statistical Society
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, a copy is available at
* https://www.R-project.org/Licenses/
*
* DESCRIPTION
*
* Compute the quantile function for the normal distribution.
*
* For small to moderate probabilities, algorithm referenced
* below is used to obtain an initial approximation which is
* polished with a final Newton step.
*
* For very large arguments, an algorithm of Wichura is used.
*
* REFERENCE
*
* Beasley, J. D. and S. G. Springer (1977).
* Algorithm AS 111: The percentage points of the normal distribution,
* Applied Statistics, 26, 118-121.
*
* Wichura, M.J. (1988).
* Algorithm AS 241: The Percentage Points of the Normal Distribution.
* Applied Statistics, 37, 477-484.
*/
/**
Computes the quantile function for the normal distribution.
Adapted from: https://svn.r-project.org/R/trunk/src/nmath/qnorm.c
- parameter p: The probability.
- parameter μ: The mean.
- parameter σ: The standard deviation.
- returns: The quantile function for the normal distribution. Returns nil if σ is zero or negative. Returns nil if p is negative or greater than one. Returns (-Double.infinity) if p is zero. Returns Double.infinity if p is one.
*/
static func qnorm(p: Double, mu: Double, sigma: Double) -> Double? {
if (p < 0 || p > 1) { return nil }
if (p == 0) { return -Double.infinity }
if (p == 1) { return Double.infinity }
if (sigma <= 0) { return nil }
let q = p - 0.5
var val: Double = 0, r: Double = 0
if (abs(q) <= 0.425) // 0.075 <= p <= 0.925
{
r = 0.180625 - q * q;
val = q * (((((((r * 2509.0809287301226727 +
33430.575583588128105) * r + 67265.770927008700853) * r +
45921.953931549871457) * r + 13731.693765509461125) * r +
1971.5909503065514427) * r + 133.14166789178437745) * r +
3.387132872796366608)
/ (((((((r * 5226.495278852854561 +
28729.085735721942674) * r + 39307.89580009271061) * r +
21213.794301586595867) * r + 5394.1960214247511077) * r +
687.1870074920579083) * r + 42.313330701600911252) * r + 1.0);
} else /* closer than 0.075 from {0,1} boundary */
{
r = q > 0 ? 1 - p : p;
r = sqrt(-log(r))
if (r <= 5) // <==> min(p,1-p) >= exp(-25) ~= 1.3888e-11
{
r -= 1.6;
val = (((((((r * 7.7454501427834140764e-4 +
0.0227238449892691845833) * r + 0.24178072517745061177) *
r + 1.27045825245236838258) * r +
3.64784832476320460504) * r + 5.7694972214606914055) *
r + 4.6303378461565452959) * r +
1.42343711074968357734)
/ (((((((r *
1.05075007164441684324e-9 + 5.475938084995344946e-4) *
r + 0.0151986665636164571966) * r +
0.14810397642748007459) * r + 0.68976733498510000455) *
r + 1.6763848301838038494) * r +
2.05319162663775882187) * r + 1.0);
}
else // very close to 0 or 1
{
r -= 5.0;
val = (((((((r * 2.01033439929228813265e-7 +
2.71155556874348757815e-5) * r +
0.0012426609473880784386) * r + 0.026532189526576123093) *
r + 0.29656057182850489123) * r +
1.7848265399172913358) * r + 5.4637849111641143699) *
r + 6.6579046435011037772)
/ (((((((r *
2.04426310338993978564e-15 + 1.4215117583164458887e-7) *
r + 1.8463183175100546818e-5) * r +
7.868691311456132591e-4) * r + 0.0148753612908506148525)
* r + 0.13692988092273580531) * r +
0.59983220655588793769) * r + 1.0);
}
if (q < 0.0) { val = -val; }
}
return (mu + sigma * val)
}
}
// ----------------------------
//
// CentralMoment.swift
//
// ----------------------------
//
// Created by Alan James Salmoni on 19/12/2016.
// Copyright © 2016 Thought Into Design Ltd. All rights reserved.
//
import Foundation
public extension Sigma {
/**
Computes central moment of the dataset.
https://en.wikipedia.org/wiki/Central_moment
- parameter values: Array of decimal numbers.
- parameter order: The order of the moment (0, 1, 2, 3 etc.).
- returns: Central moment. Returns nil when the array is empty.
Formula:
Σ(x - m)^k / n
Where:
m is the sample mean.
k is the order of the moment (0, 1, 2, 3, ...).
n is the sample size.
Example:
Sigma.centralMoment([3, -1, 1, 4.1, 4.1, 0.7], order: 3) // -1.5999259259
*/
static func centralMoment(_ values: [Double], order: Int) -> Double? {
let count = Double(values.count)
if count == 0 { return nil }
guard let averageVal = average(values) else { return nil }
let total = values.reduce(0) { sum, value in
sum + pow((value - averageVal), Double(order))
}
return total / count
}
}
// ----------------------------
//
// Covariance.swift
//
// ----------------------------
import Foundation
public extension Sigma {
/**
Computes covariance of a sample between two variables: x and y.
http://en.wikipedia.org/wiki/Sample_mean_and_sample_covariance
- parameter x: Array of decimal numbers for the first variable.
- parameter y: Array of decimal numbers for the second variable.
- returns: Covariance of a sample between two variables: x and y. Returns nil if arrays x and y have different number of values. Returns nil for empty arrays or arrays containing a single element.
Formula:
cov(x,y) = Σ(x - mx)(y - my) / (n - 1)
Where:
mx is the sample mean of the first variable.
my is the sample mean of the second variable.
n is the total number of values.
Example:
let x = [1, 2, 3.5, 3.7, 8, 12]
let y = [0.5, 1, 2.1, 3.4, 3.4, 4]
Sigma.covarianceSample(x: x, y: y) // 5.03
*/
static func covarianceSample(x: [Double], y: [Double]) -> Double? {
let xCount = Double(x.count)
let yCount = Double(y.count)
if xCount < 2 { return nil }
if xCount != yCount { return nil }
if let xMean = average(x),
let yMean = average(y) {
var sum:Double = 0
for (index, xElement) in x.enumerated() {
let yElement = y[index]
sum += (xElement - xMean) * (yElement - yMean)
}
return sum / (xCount - 1)
}
return nil
}
/**
Computes covariance for entire population between two variables: x and y.
http://en.wikipedia.org/wiki/Covariance
- parameter x: Array of decimal numbers for the first variable.
- parameter y: Array of decimal numbers for the second variable.
- returns: Covariance for entire population between two variables: x and y. Returns nil if arrays x and y have different number of values. Returns nil for empty arrays.
Formula:
cov(x,y) = Σ(x - mx)(y - my) / n
Where:
mx is the population mean of the first variable.
my is the population mean of the second variable.
n is the total number of values.
Example:
let x = [1, 2, 3.5, 3.7, 8, 12]
let y = [0.5, 1, 2.1, 3.4, 3.4, 4]
Sigma.covariancePopulation(x: x, y: y) // 4.19166666666667
*/
static func covariancePopulation(x: [Double], y: [Double]) -> Double? {
let xCount = Double(x.count)
let yCount = Double(y.count)
if xCount == 0 { return nil }
if xCount != yCount { return nil }
if let xMean = average(x),
let yMean = average(y) {
var sum:Double = 0
for (index, xElement) in x.enumerated() {
let yElement = y[index]
sum += (xElement - xMean) * (yElement - yMean)
}
return sum / xCount
}
return nil
}
}
// ----------------------------
//
// Variance.swift
//
// ----------------------------
import Foundation
public extension Sigma {
/**
Computes variance based on a sample.
http://en.wikipedia.org/wiki/Variance
- parameter values: Array of decimal numbers.
- returns: Variance based on a sample. Returns nil when the array is empty or contains a single value.
Formula:
s^2 = Σ( (x - m)^2 ) / (n - 1)
Where:
m is the sample mean.
n is the sample size.
Example:
Sigma.varianceSample([1, 12, 19.5, -5, 3, 8]) // 75.24166667
*/
static func varianceSample(_ values: [Double]) -> Double? {
let count = Double(values.count)
if count < 2 { return nil }