Verify distribution uniformity/Naive: Difference between revisions

Content added Content deleted
(add Ruby)
(→‎{{header|Ruby}}: yield to a block instead of a potentially clumsy proc argument)
Line 48: Line 48:
=={{header|Ruby}}==
=={{header|Ruby}}==
{{trans|Tcl}}
{{trans|Tcl}}
<lang ruby>def distcheck(fn_proc, n, delta=1)
<lang ruby>def distcheck(n, delta=1)
unless block_given?
raise ArgumentError, "pass a block to this method"
end
h = Hash.new(0)
h = Hash.new(0)
n.times {h[fn_proc.call()] += 1}
n.times {h[ yield ] += 1}
target = 1.0 * n / h.length
target = 1.0 * n / h.length
h.each do |key, value|
h.each do |key, value|
if (value - target).abs > 0.01 * delta * n
if (value - target).abs > 0.01 * delta * n
raise StandardError,
raise StandardError,
Line 58: Line 63:
end
end
end
end
h.keys.sort.each {|k| print "#{k} #{h[k]} "}
h.keys.sort.each {|k| print "#{k} #{h[k]} "}
puts
puts
Line 63: Line 69:


if __FILE__ == $0
if __FILE__ == $0
begin
distcheck( lambda {rand(10)}, 100_000)
distcheck( lambda {rand > 0.95}, 100_000)
distcheck(100_000) {rand(10)}
distcheck(100_000) {rand > 0.95}
rescue StandardError => e
p e
end
end</lang>
end</lang>


output:
output:
<pre>0 9986 1 9826 2 9861 3 10034 4 9876 5 10114 6 10329 7 9924 8 10123 9 9927
<pre>$ ruby distcheck.rb
#<StandardError: distribution potentially skewed for 'false': expected around 50000.0, got 94841></pre>
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}}==
=={{header|Tcl}}==