Verify distribution uniformity/Naive: Difference between revisions

→‎Tcl: Added implementation
(New task and Python solution.)
 
(→‎Tcl: Added implementation)
Line 1:
{{task}}
<small>This task is an adjunct to [[Seven-dice from Five-dice]].</small>
 
 
Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.
Line 13 ⟶ 12:
* Some indication of the distribution achieved.
* An 'error' if the distribution is not flat enough.
 
 
Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from [[Seven-dice from Five-dice]]).
Line 44 ⟶ 42:
for key, count in sorted(bin.items()) ]
AssertionError: Bin distribution skewed from 200 +/- 2: [(1, 4), (2, -33), (3, 6), (4, 11), (5, 12)]</pre>
 
=={{header|Tcl}}==
<lang tcl>proc distcheck {random times {delta 1}} {
for {set i 0} {$i<$times} {incr i} {incr vals([uplevel 1 $random])}
set target [expr {$times / [array size vals]}]
foreach {k v} [array get vals] {
if {abs($v - $target) > $times * $delta / 100.0} {
error "distribution potentially skewed for $k: expected around $target, got $v"
}
}
foreach k [lsort -integer [array names vals]] {lappend result $k $vals($k)}
return $result
}</lang>
Demonstration:
<lang tcl># First, a uniformly distributed random variable
puts [distcheck {expr {int(10*rand())}} 100000]
 
# Now, one that definitely isn't!
puts [distcheck {expr {rand()>0.95}} 100000]</lang>
Which produces this output (error in red):
0 10003 1 9851 2 10058 3 10193 4 10126 5 10002 6 9852 7 9964 8 9957 9 9994
<span style="color:red">distribution potentially skewed for 0: expected around 50000, got 94873</span>
Anonymous user