How to resolve the algorithm Cumulative standard deviation step by step in the Scala programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Cumulative standard deviation step by step in the Scala programming language
Table of Contents
Problem Statement
Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task must state which is being used. Do not apply Bessel's correction; the returned standard deviation should always be computed as if the sample seen so far is the entire population.
Use this to compute the standard deviation of this demonstration set,
{ 2 , 4 , 4 , 4 , 5 , 5 , 7 , 9 }
{\displaystyle {2,4,4,4,5,5,7,9}}
, which is
2
{\displaystyle 2}
.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Cumulative standard deviation step by step in the Scala programming language
Source code in the scala programming language
import scala.math.sqrt
object StddevCalc extends App {
def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {
def avg(ts: Iterable[T])(implicit num: Fractional[T]): T =
num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T
val mean: T = avg(ts) // Leave val type of T
// Root of mean diffs
val stdDev = sqrt(ts.map { x =>
val diff = num.toDouble(num.minus(x, mean))
diff * diff
}.sum / ts.size)
(mean, stdDev)
}
println(calcAvgAndStddev(List(2.0E0, 4.0, 4, 4, 5, 5, 7, 9)))
println(calcAvgAndStddev(Set(1.0, 2, 3, 4)))
println(calcAvgAndStddev(0.1 to 1.1 by 0.05))
println(calcAvgAndStddev(List(BigDecimal(120), BigDecimal(1200))))
println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]")
}
You may also check:How to resolve the algorithm Erdős-Nicolas numbers step by step in the Go programming language
You may also check:How to resolve the algorithm Deal cards for FreeCell step by step in the Befunge programming language
You may also check:How to resolve the algorithm Sierpinski carpet step by step in the BQN programming language
You may also check:How to resolve the algorithm Averages/Pythagorean means step by step in the Oforth programming language
You may also check:How to resolve the algorithm Factorial step by step in the Janet programming language