commonMain.ru.casperix.math.function.FunctionStatistic.kt Maven / Gradle / Ivy
package ru.casperix.math.function
import ru.casperix.math.axis_aligned.int32.Box2i
import kotlin.math.pow
import kotlin.math.sqrt
class FunctionStatistic(val capacity: Int? = null) {
private val values = mutableListOf()
val size get() = values.size
val average: Double
get() {
val valueAccumulated = values.fold(0.0) { a, b -> a + b }
return valueAccumulated / values.size
}
val dispersion: Double
get() {
if (values.isEmpty()) return Double.NaN
val average = this.average
var D = 0.0
values.forEach { value ->
D += (average - value).pow(2)
}
D /= size
return D
}
val standardDeviation get() = sqrt(dispersion)
val min: Double
get() {
return values.minOrNull() ?: Double.NaN
}
val max: Double
get() {
return values.maxOrNull() ?: Double.NaN
}
fun add(value: Double) {
values.add(value)
if (capacity != null) {
while (values.size > capacity) {
values.removeFirst()
}
}
}
companion object {
fun calculate(input: Function2D, area: Box2i): FunctionStatistic {
val statistic = FunctionStatistic()
for (pos in area) {
val value = input(pos.x.toDouble(), pos.y.toDouble())
statistic.add(value)
}
return statistic
}
}
}