Verify distribution uniformity/Naive: Difference between revisions

Content added Content deleted
Line 1,197: Line 1,197:
=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import random, tables
<lang Nim>import random, tables



proc checkDist(f: proc(): int; repeat: Positive; tolerance: float) =
proc checkDist(f: proc(): int; repeat: Positive; tolerance: float) =

var counts: CountTable[int]
var counts: CountTable[int]
for _ in 1..repeat:
for _ in 1..repeat:
counts.inc f()
counts.inc f()

let expected = (repeat / counts.len).toInt # Rounded to nearest.
let expected = (repeat / counts.len).toInt # Rounded to nearest.
let allowedDelta = (expected.toFloat * tolerance / 100).toInt
let allowedDelta = (expected.toFloat * tolerance / 100).toInt
Line 1,208: Line 1,211:
let d = abs(count - expected)
let d = abs(count - expected)
if d > maxDelta: maxDelta = d
if d > maxDelta: maxDelta = d
let status = if maxDelta <= allowedDelta: "passed" else: "failed"
let status = if maxDelta <= allowedDelta: "passed" else: "failed"
echo "Checking with a tolerance of ", tolerance, "%."
echo "Checking with a tolerance of ", tolerance, "%."
Line 1,218: Line 1,222:
randomize()
randomize()
proc rand5(): int = rand(1..5)
proc rand5(): int = rand(1..5)
checkDist(rand5, 1_000_000, 0.5)</lang>
checkDist(rand5, 1_000_000, 0.5)
</lang>


{{out}}
{{out}}