Verify distribution uniformity/Naive: Difference between revisions
Content added Content deleted
m (added whitespace before the TOC (table of contents), added a ;Task: (bold) header.) |
(Added Kotlin) |
||
Line 968: | Line 968: | ||
distribution potentially skewed for 0: expected result around 50000, got 95040</pre> |
distribution potentially skewed for 0: expected result around 50000, got 95040</pre> |
||
=={{header|Kotlin}}== |
|||
<lang scala>// version 1.1.3 |
|||
import java.util.Random |
|||
val r = Random() |
|||
fun dice5() = 1 + r.nextInt(5) |
|||
fun checkDist(gen: () -> Int, nRepeats: Int, tolerance: Double = 0.5) { |
|||
val occurs = mutableMapOf<Int, Int>() |
|||
for (i in 1..nRepeats) { |
|||
val d = gen() |
|||
if (occurs.containsKey(d)) |
|||
occurs[d] = occurs[d]!! + 1 |
|||
else |
|||
occurs.put(d, 1) |
|||
} |
|||
val expected = (nRepeats.toDouble()/ occurs.size).toInt() |
|||
val maxError = (expected * tolerance / 100.0).toInt() |
|||
println("Repetitions = $nRepeats, Expected = $expected") |
|||
println("Tolerance = $tolerance%, Max Error = $maxError\n") |
|||
println("Integer Occurrences Error Acceptable") |
|||
val f = " %d %5d %5d %s" |
|||
var allAcceptable = true |
|||
for ((k,v) in occurs.toSortedMap()) { |
|||
val error = Math.abs(v - expected) |
|||
val acceptable = if (error <= maxError) "Yes" else "No" |
|||
if (acceptable == "No") allAcceptable = false |
|||
println(f.format(k, v, error, acceptable)) |
|||
} |
|||
println("\nAcceptable overall: ${if (allAcceptable) "Yes" else "No"}") |
|||
} |
|||
fun main(args: Array<String>) { |
|||
checkDist(::dice5, 1_000_000) |
|||
println() |
|||
checkDist(::dice5, 100_000) |
|||
}</lang> |
|||
Sample output: |
|||
<pre> |
|||
Repetitions = 1000000, Expected = 200000 |
|||
Tolerance = 0.5%, Max Error = 1000 |
|||
Integer Occurrences Error Acceptable |
|||
1 200074 74 Yes |
|||
2 200497 497 Yes |
|||
3 199295 705 Yes |
|||
4 199822 178 Yes |
|||
5 200312 312 Yes |
|||
Acceptable overall: Yes |
|||
Repetitions = 100000, Expected = 20000 |
|||
Tolerance = 0.5%, Max Error = 100 |
|||
Integer Occurrences Error Acceptable |
|||
1 20265 265 No |
|||
2 20229 229 No |
|||
3 19836 164 No |
|||
4 19931 69 Yes |
|||
5 19739 261 No |
|||
Acceptable overall: No |
|||
</pre> |
|||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |