1
+ package com.baeldung.math.standardDeviation
2
+ import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation
3
+ import org.junit.jupiter.api.Assertions.assertEquals
4
+ import org.junit.jupiter.api.Test
5
+ import kotlin.math.pow
6
+
7
+ class StandardDeviationUnitTest {
8
+
9
+ @Test
10
+ fun `standard deviation using the math package` () {
11
+ val dataset1 = doubleArrayOf(1.0 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 )
12
+ val dataset2 = doubleArrayOf(11.0 , 14.0 , 19.0 , 23.0 , 28.0 , 30.0 )
13
+
14
+ assertEquals(1.707825127659933 , standardDeviationUsingMathPackage(dataset1))
15
+ assertEquals(6.914156170897181 , standardDeviationUsingMathPackage(dataset2))
16
+ }
17
+
18
+ @Test
19
+ fun `standard deviation using the apache commons math library` () {
20
+ val dataset1 = doubleArrayOf(1.0 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 )
21
+ val dataset2 = doubleArrayOf(11.0 , 14.0 , 19.0 , 23.0 , 28.0 , 30.0 )
22
+
23
+ assertEquals(1.707825127659933 , calculateStandardDeviationUsingApacheCommonsMath(dataset1))
24
+ assertEquals(6.914156170897181 , calculateStandardDeviationUsingApacheCommonsMath(dataset2))
25
+ }
26
+
27
+
28
+ fun standardDeviationUsingMathPackage (dataset : DoubleArray ): Double {
29
+ val mean = dataset.average()
30
+ val variance = dataset.map { (it - mean).pow(2 ) }.average()
31
+ return Math .sqrt(variance)
32
+ }
33
+
34
+ fun calculateStandardDeviationUsingApacheCommonsMath (dataset : DoubleArray ): Double {
35
+ val sd = StandardDeviation (false )
36
+
37
+ return sd.evaluate(dataset)
38
+ }
39
+ }
0 commit comments