RosettaCodeData/Task/Random-numbers/Scala/random-numbers-2.scala

29 lines
793 B
Scala
Raw Permalink Normal View History

2020-02-17 23:21:07 -08:00
object RandomNumbers extends App {
2018-06-22 20:57:24 +00:00
2020-02-17 23:21:07 -08:00
val distribution: LazyList[Double] = {
def randomNormal: Double = 1.0 + 0.5 * scala.util.Random.nextGaussian
2018-06-22 20:57:24 +00:00
2020-02-17 23:21:07 -08:00
def normalDistribution(a: Double): LazyList[Double] = a #:: normalDistribution(randomNormal)
normalDistribution(randomNormal)
}
2018-06-22 20:57:24 +00:00
2020-02-17 23:21:07 -08:00
/*
* Let's test it
*/
2018-06-22 20:57:24 +00:00
def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = {
val mean: T =
num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T
// Root of mean diffs
2020-02-17 23:21:07 -08:00
val stdDev = Math.sqrt(ts.map { x =>
2018-06-22 20:57:24 +00:00
val diff = num.toDouble(num.minus(x, mean))
diff * diff
}.sum / ts.size)
(mean, stdDev)
}
2020-02-17 23:21:07 -08:00
println(calcAvgAndStddev(distribution.take(1000))) // e.g. (1.0061433267806525,0.5291834867560893)
}