Created
October 28, 2019 07:55
-
-
Save patio11/546c64c927c749c69964b18527fabe30 to your computer and use it in GitHub Desktop.
monte carlo simulation for perl random line generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NUMBER_OF_BUCKETS = 100 | |
EXPECTED_BUCKET_SIZE = 100 | |
file = "1-to-#{NUMBER_OF_BUCKETS}.txt" | |
f = File.open(file, "w") | |
contents = (1..NUMBER_OF_BUCKETS).to_a.map(&:to_s).join("\n") | |
f.write(contents) | |
f.close() | |
command = "cat #{file} | perl -e 'while(<>){$x=$_ if rand()<=(1/$.)}print $x'" | |
outcomes = {} | |
EXPECTED_BUCKET_SIZE.times do |i| | |
puts "#{i} iteration out of #{EXPECTED_BUCKET_SIZE}" | |
NUMBER_OF_BUCKETS.times do | |
believed_to_be_random_number = `#{command}`.to_i | |
outcomes[believed_to_be_random_number] ||= 0 | |
outcomes[believed_to_be_random_number] += 1 | |
end | |
end | |
puts "Each of these should be approximately #{EXPECTED_BUCKET_SIZE}." | |
test_points = outcomes.to_a.shuffle[0..24] | |
test_points.each do |pt| | |
a, b = pt | |
puts "#{a} had #{b} occurrences." | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment