Skip to content

Commit 5c0b03f

Browse files
authored
KTLN-694: Calculate Standard Deviation in Kotlin (#756)
* pom kotlin version * addedd unit tests * fixed unit tests
1 parent 47b9795 commit 5c0b03f

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

kotlin-math-2/pom.xml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,12 @@
1212
<artifactId>kotlin-modules</artifactId>
1313
<version>1.0.0-SNAPSHOT</version>
1414
</parent>
15+
16+
<dependencies>
17+
<dependency>
18+
<groupId>org.apache.commons</groupId>
19+
<artifactId>commons-math3</artifactId>
20+
<version>3.6.1</version>
21+
</dependency>
22+
</dependencies>
1523
</project>
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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

Comments
 (0)