Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions kotlin-math-2/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,12 @@
<artifactId>kotlin-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>

<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.baeldung.math.standardDeviation
import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import kotlin.math.pow

class StandardDeviationUnitTest {

@Test
fun `standard deviation using the math package`() {
val dataset1 = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)
val dataset2 = doubleArrayOf(11.0, 14.0, 19.0, 23.0, 28.0, 30.0)

assertEquals(1.707825127659933, standardDeviationUsingMathPackage(dataset1))
assertEquals(6.914156170897181, standardDeviationUsingMathPackage(dataset2))
}

@Test
fun `standard deviation using the apache commons math library`() {
val dataset1 = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0)
val dataset2 = doubleArrayOf(11.0, 14.0, 19.0, 23.0, 28.0, 30.0)

assertEquals(1.707825127659933, calculateStandardDeviationUsingApacheCommonsMath(dataset1))
assertEquals(6.914156170897181, calculateStandardDeviationUsingApacheCommonsMath(dataset2))
}


fun standardDeviationUsingMathPackage(dataset: DoubleArray): Double {
val mean = dataset.average()
val variance = dataset.map { (it - mean).pow(2) }.average()
return Math.sqrt(variance)
}

fun calculateStandardDeviationUsingApacheCommonsMath(dataset: DoubleArray): Double {
val sd = StandardDeviation(false)

return sd.evaluate(dataset)
}
}