Verify distribution uniformity/Naive: Difference between revisions

added Icon/Unicon example
(GP)
(added Icon/Unicon example)
Line 366:
(5,(16526,True))
(6,(16670,True))</lang>
 
=={{header|Icon}} and {{header|Unicon}}==
 
This example assumes the random number generator is passed to <code>verify_uniform</code> as a co-expression. The co-expression <code>rnd</code> is prompted for its next value using <code>@rnd</code>. The co-expression is created using <code>create (|?10)</code> where the vertical bar means generate an infinite sequence of what is to its right (in this case, <code>?10</code> generates a random integer in the range [1,10]).
 
<lang Icon>
# rnd : a co-expression, which will generate the random numbers
# n : the number of numbers to test
# delta: tolerance in non-uniformity
# This procedure fails if after the sampling the difference
# in uniformity exceeds delta, a proportion of n / number-of-alternatives
procedure verify_uniform (rnd, n, delta)
# generate a table counting the outcome of the generator
results := table (0)
every (1 to n) do results[@rnd] +:= 1
# retrieve the statistics
smallest := n
largest := 0
every num := key(results) do { # record result and limits
write (num || " " || results[num])
if results[num] < smallest then smallest := results[num]
if results[num] > largest then largest := results[num]
}
# decide if difference is within bounds defined by delta
return largest-smallest < delta * n / *results
end
 
procedure main ()
gen_1 := create (|?10) # uniform integers, 1 to 10
if verify_uniform (gen_1, 1000000, 0.01)
then write ("uniform")
else write ("skewed")
gen_2 := create (|(if ?2 = 1 then 6 else ?10)) # skewed integers, 1 to 10
if verify_uniform (gen_2, 1000000, 0.01)
then write ("uniform")
else write ("skewed")
end
</lang>
 
Output:
<pre>
5 99988
2 99998
10 99894
7 99948
4 100271
1 99917
9 99846
6 99943
3 99824
8 100371
uniform
5 49940
2 50324
10 50243
7 49982
4 50295
1 50162
9 49800
6 549190
3 50137
8 49927
skewed
</pre>
 
=={{header|J}}==
342

edits