1
\$\begingroup\$

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 )
}
\$\endgroup\$
2
\$\begingroup\$

You may want to be more idiomatic when working with collections, for an instance:

fun sd(numArray: DoubleArray): Double {
    val mean = numArray.average()
    val sd = numArray.fold(0.0, { accumulator, next -> accumulator + Math.pow(next - mean, 2.0) })
    return Math.sqrt(sd / numArray.size)
}

BTW, I don't think that numArray.size - 1 is correct

\$\endgroup\$
  • \$\begingroup\$ There are two kinds of standard deviation. The sample standard deviation involves dividing by N - 1. \$\endgroup\$ – 200_success Dec 17 '17 at 23:13
  • \$\begingroup\$ True: en.wikipedia.org/wiki/Bessel%27s_correction . Do you think that this is the case here ? \$\endgroup\$ – David Soroko Dec 17 '17 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 Dec 17 '17 at 23:29
  • \$\begingroup\$ I didn't do use the word wrong. \$\endgroup\$ – David Soroko Dec 17 '17 at 23:30
1
\$\begingroup\$

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).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.