Monte Carlo Simulation: pi

Tags:

if ARGV.length == 0
puts “USAGE: #{__FILE__} [# of iterations]”
exit 0
end

def rand_point
[rand, rand]
end

def inside_circle?(p)
p[0] ** 2 + p[1] ** 2 <= 1 end def pi_val(total_run, inside_cnt) inside_cnt.to_f / total_run * 4 end def report_pi(total_run, inside_cnt) puts "#{total_run}: pi = #{pi_val(total_run, inside_cnt)}" end total_run = 0 inside_cnt = 0; 1.upto(ARGV[0].to_i) do total_run += 1 inside_cnt +=1 if inside_circle?(rand_point) report_pi(total_run, inside_cnt) if total_run % 1000 == 0 end report_pi(total_run, inside_cnt) [/code] 결과는 [code lang="cpp"] ... 3000000: pi = 3.14197466666667 ... [/code]