diff --git a/kmath-core/src/commonMain/kotlin/scientifik/kmath/stat/Stat.kt b/kmath-core/src/commonMain/kotlin/scientifik/kmath/stat/Stat.kt new file mode 100644 index 000000000..d956f29c2 --- /dev/null +++ b/kmath-core/src/commonMain/kotlin/scientifik/kmath/stat/Stat.kt @@ -0,0 +1,71 @@ +package scientifik.kmath.stat + +import scientifik.kmath.operations.Field +import scientifik.kmath.operations.RealField +import scientifik.kmath.operations.Ring +import scientifik.kmath.operations.Space +import scientifik.kmath.structures.NDStructure +import kotlin.math.pow + + + + +// TODO tailrec +fun Ring.pow(element : T, n : Int) : T { + if (n == 0 ){ + return one + } + if (n==1){ + return element + } + val temp = pow(element, n / 2) + return if (n%2==0) temp*temp else element*temp*temp +} + +//fun NDStructure.map(transform : (T) -> R) : NDStructure{ +// +//} + + +/** + * Context for sequence-like operations + */ +class CollectionsOperations(val context: Space){ + fun sum(structure: NDStructure): T { + return with(context){ + var sum = zero + for (element in structure.elements()) { + sum += element.second + } + sum + } + } + +} + +/** + * Context for statistical operations + */ +open class Statistical(val context : Field){ + fun mean(data : NDStructure) = moment(data, 1) + + fun variance(data: NDStructure) = centralMomentum(data, 2) + + fun moment(data: NDStructure, k : Int) : T{ + return with(context){ + var result = zero + val number = data.shape.reduce { acc, i -> acc*i } + for (element in data.elements()){ + result += pow(element.second, k) + } + result/number + } + } + + fun centralMomentum(data: NDStructure, k: Int) = with(context){moment(data, k) - pow(mean(data), k)} + +} + +class RealStatistical : Statistical(RealField){ + fun std(data : NDStructure) = with(context){variance(data).pow(0.5)} +} \ No newline at end of file