Verify distribution uniformity/Naive: Difference between revisions

add Ruby
(Remove chi-squared stuff to another task, add cross-link)
(add Ruby)
Line 45:
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|Ruby}}==
{{trans|Tcl}}
<lang ruby>def distcheck(fn_proc, n, delta=1)
h = Hash.new(0)
n.times {h[fn_proc.call()] += 1}
target = 1.0 * n / h.length
h.each do |key, value|
if (value - target).abs > 0.01 * delta * n
raise StandardError,
"distribution potentially skewed for '#{key}': expected around #{target}, got #{value}"
end
end
h.keys.sort.each {|k| print "#{k} #{h[k]} "}
puts
end
 
if __FILE__ == $0
distcheck( lambda {rand(10)}, 100_000)
distcheck( lambda {rand > 0.95}, 100_000)
end</lang>
 
output:
<pre>$ ruby distcheck.rb
0 9865 1 10026 2 10204 3 9847 4 10190 5 9848 6 9999 7 9986 8 10011 9 10024
distcheck.rb:7:in `distcheck': distribution potentially skewed for 'false': expected around 50000.0, got 94912 (StandardError)</pre>
 
=={{header|Tcl}}==
Anonymous user