Anonymous user
Cumulative standard deviation: Difference between revisions
m
-Category:Scala Implementations / moved SAS before Scala
m (Random_numbers) |
m (-Category:Scala Implementations / moved SAS before Scala) |
||
Line 2,361:
7 value in = 7 Stand Dev = 1.399708
8 value in = 9 Stand Dev = 2.000000</pre>
=={{header|Scala}}==▼
{{libheader|Scala}}▼
<lang Scala>import scala.math._▼
import Numeric.Implicits._▼
object StddevCalc extends App {▼
def avg[T](ts: Iterable[T])(implicit num: Fractional[T]): T = {▼
num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T▼
}▼
def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {▼
val mean = avg(ts) // Leave val type of T▼
val stdDev = // Root of mean diffs▼
sqrt(num.toDouble(ts.foldLeft(num.zero)((b, a) => num.plus(b, num.times(num.minus(a, mean), num.minus(a, mean))))) / ts.size)▼
(mean, stdDev)▼
}▼
def calcAvgAndStddev(ts: Iterable[BigDecimal]): (Double, Double) = // Overloaded for BigDecimal▼
calcAvgAndStddev(ts.map(_.toDouble))▼
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))))▼
}</lang>▼
=={{header|SAS}}==
Line 2,440 ⟶ 2,411:
8 2.00000
</pre>
▲=={{header|Scala}}==
▲{{libheader|Scala}}
▲<lang Scala>import scala.math._
▲import Numeric.Implicits._
▲object StddevCalc extends App {
▲ def avg[T](ts: Iterable[T])(implicit num: Fractional[T]): T = {
▲ num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T
▲ }
▲ def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {
▲ val mean = avg(ts) // Leave val type of T
▲ val stdDev = // Root of mean diffs
▲ sqrt(num.toDouble(ts.foldLeft(num.zero)((b, a) => num.plus(b, num.times(num.minus(a, mean), num.minus(a, mean))))) / ts.size)
▲ (mean, stdDev)
▲ }
▲ def calcAvgAndStddev(ts: Iterable[BigDecimal]): (Double, Double) = // Overloaded for BigDecimal
▲ calcAvgAndStddev(ts.map(_.toDouble))
▲ 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))))
▲}</lang>
=={{header|Scheme}}==
|