Here is the code. The code should counts the standard deviation for double array, but also for Int arrays.
fun calculateSD(numArray: DoubleArray): Double {
var sum = 0.0
var standardDeviation = 0.0
for (num in numArray) {
sum += num
}
val mean = sum / numArray.size
for (num in numArray) {
standardDeviation += Math.pow(num - mean, 2.0)
}
val divider = numArray.size - 1
return Math.sqrt(standardDeviation / divider )
}
2 Answers 2
You may want to be more idiomatic when working with collections, for instance:
import kotlin.math.pow
import kotlin.math.sqrt
fun sd(data: DoubleArray): Double {
val mean = data.average()
return data
.fold(0.0, { accumulator, next -> accumulator + (next - mean).pow(2.0) })
.let { sqrt(it / data.size )
}
}
BTW, I don't think that data.size - 1
is correct
-
1\$\begingroup\$ There are two kinds of standard deviation. The sample standard deviation involves dividing by N - 1. \$\endgroup\$200_success– 200_success2017年12月17日 23:13:19 +00:00Commented Dec 17, 2017 at 23:13
-
\$\begingroup\$ True: en.wikipedia.org/wiki/Bessel%27s_correction . Do you think that this is the case here ? \$\endgroup\$David Soroko– David Soroko2017年12月17日 23:27:45 +00:00Commented Dec 17, 2017 at 23:27
-
\$\begingroup\$ You could complain about unclear naming or lack of documentation for this function, but I'd hesitate to call it "wrong". \$\endgroup\$200_success– 200_success2017年12月17日 23:29:08 +00:00Commented Dec 17, 2017 at 23:29
-
\$\begingroup\$
data.sumOf { (next - mean).pow(2) }
instead ofaggregate
is simpler, but requires kotlin 1.4. \$\endgroup\$Groostav– Groostav2023年08月09日 21:55:12 +00:00Commented Aug 9, 2023 at 21:55 -
\$\begingroup\$ Did you mean "instead of fold" ? \$\endgroup\$David Soroko– David Soroko2023年08月10日 19:43:53 +00:00Commented Aug 10, 2023 at 19:43
Performance
Something to consider (in general) is whether Math.pow(x, 2.0)
is going to be optimized by the interpreter/compiler into x * x
or not. The former can be slower if, say, it is computed as Math.exp(Math.log(x) * 2.0)
.