I wrote this toy program to help my daughter with a science project. She ended up not using it but I think the output looks cool. It requires gruff, IMagick, and RMagick to run. Though it contains variables that have to be edited to alter the output, I think the names are clear enough that you can see what they do. The language is Ruby if that's not obvious. I apologize for the lack of indentation, I guess you lose formatting information when you cut and paste from TextEdit.
require 'rubygems'
require 'gruff'
if argv[0] == nil
number_of_runs = 100000
else
number_or_runs = argv[0]
flips_per_run = 10
bias_factor = 0
flips = Array.new(flips_per_run,0)
run_results = Array.new(flips_per_run + 1,0)
(1..number_of_runs).each do
flips.each_index do |i|
if (rand + bias_factor) > 0.5
flips[i] = 1
else
flips[i] = 0
end
end
run_results[flips.count(1)] = run_results[flips.count(1)] + 1
end
flips_per_run.downto(0) do |size|
run_results.each_index do |index|
if run_results[index] / (number_of_runs/flips_per_run)>= size then
print "*"
else
print " "
end
end
print "\n"
end
run_results.each_index{ |i| print run_results[i]," "}
print "\n"
g = Gruff::Line.new
g.title = "Data for " + number_of_runs.to_s + " Runs of " + flips_per_run.to_s + " Flips"
if flips_per_run < 50
label_hash = Hash.new
(0..flips_per_run).each { |i| label_hash[i] = i.to_s}
g.labels = label_hash
end
g.data("Number of runs with x heads",run_results)
g.write("penny_graph.png")
print "\n"
No comments:
Post a Comment