Skip to content

Instantly share code, notes, and snippets.

@patio11
Created October 28, 2019 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patio11/546c64c927c749c69964b18527fabe30 to your computer and use it in GitHub Desktop.
Save patio11/546c64c927c749c69964b18527fabe30 to your computer and use it in GitHub Desktop.
monte carlo simulation for perl random line generator
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