Skip to content

Commit

Permalink
expanded std with BigInteger and Number
Browse files Browse the repository at this point in the history
  • Loading branch information
Jolanrensen committed Nov 7, 2024
1 parent 4d4ebda commit 2ef56b4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import org.jetbrains.kotlinx.dataframe.api.ddof_default
import org.jetbrains.kotlinx.dataframe.api.skipNA_default
import org.jetbrains.kotlinx.dataframe.impl.renderType
import java.math.BigDecimal
import java.math.BigInteger
import kotlin.reflect.KType
import kotlin.reflect.full.withNullability

Expand All @@ -26,6 +27,8 @@ internal fun <T : Number> Iterable<T?>.std(
Int::class, Short::class, Byte::class -> (this as Iterable<Int>).std(ddof)
Long::class -> (this as Iterable<Long>).std(ddof)
BigDecimal::class -> (this as Iterable<BigDecimal>).std(ddof)
BigInteger::class -> (this as Iterable<BigInteger>).std(ddof)
Number::class -> (this as Iterable<Number>).map { it.toDouble() }.std(skipNA, ddof)
Nothing::class -> Double.NaN
else -> throw IllegalArgumentException("Unable to compute the std for type ${renderType(type)}")
}
Expand All @@ -47,3 +50,6 @@ public fun Iterable<Long>.std(ddof: Int = ddof_default): Double = varianceAndMea

@JvmName("bigDecimalStd")
public fun Iterable<BigDecimal>.std(ddof: Int = ddof_default): Double = varianceAndMean().std(ddof)

@JvmName("bigIntegerStd")
public fun Iterable<BigInteger>.std(ddof: Int = ddof_default): Double = varianceAndMean().std(ddof)
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package org.jetbrains.kotlinx.dataframe.math

import org.jetbrains.kotlinx.dataframe.api.skipNA_default
import java.math.BigDecimal
import java.math.BigInteger
import kotlin.math.sqrt

public data class BasicStats(val count: Int, val mean: Double, val variance: Double) {
Expand Down Expand Up @@ -114,3 +115,20 @@ public fun Iterable<BigDecimal>.varianceAndMean(): BasicStats {
}
return BasicStats(count, mean.toDouble(), variance.toDouble())
}

@JvmName("bigIntegerVarianceAndMean")
public fun Iterable<BigInteger>.varianceAndMean(): BasicStats {
var count = 0
var sum = BigInteger.ZERO
for (element in this) {
sum += element
count++
}
val mean = sum.toDouble() / count
var variance = .0
for (element in this) {
val diff = element.toDouble() - mean
variance += diff * diff
}
return BasicStats(count, mean, variance)
}

0 comments on commit 2ef56b4

Please sign in to comment.