Random numbers: Difference between revisions
Content added Content deleted
(→Alternate solution: remove code that doesn't address the problem, and vanity badge.) |
|||
Line 1,938: | Line 1,938: | ||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
===One liner=== |
|||
<lang scala>List.fill(1000)(1.0 + 0.5 * scala.util.Random.nextGaussian)</lang> |
<lang scala>List.fill(1000)(1.0 + 0.5 * scala.util.Random.nextGaussian)</lang> |
||
===Academic=== |
|||
<lang scala>val distrubution = { |
|||
def randomNormal = 1.0 + 0.5 * scala.util.Random.nextGaussian |
|||
def normalDistribution(a: Double): Stream[Double] = a #:: normalDistribution(randomNormal) |
|||
normalDistribution(randomNormal) |
|||
} |
|||
/* |
|||
* Let's test it |
|||
*/ |
|||
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 |
|||
} |
|||
def mean = avg(ts) |
|||
def stdDev = // Root of mean diffs |
|||
math.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) |
|||
} |
|||
println(calcAvgAndStddev(distrubution.take(1000))) // e.g. (1.0061433267806525,0.5291834867560893)</lang> |
|||
=={{header|Scheme}}== |
=={{header|Scheme}}== |