モンテカルロ法で円周率を求める
http://hp.vector.co.jp/authors/VA014765/image/monte.gif
code:pi.js
var canvas = $('<canvas>');
canvas.css('position','absolute');
canvas.css('left',100).css('top',100).attr('width',400).attr('height',400).css('z-index','100');
canvas.css('background-color','#ff0');
$('body').append(canvas);
var context = canvas0.getContext('2d'); var val = $('<span>');
val.css('position','absolute');
val.css('left',100).css('top',100).attr('width',400).attr('height',400).css('z-index','100');
val.css('background-color','#eee');
$('body').append(val);
total = 0;
inner = 0;
context.fillStyle = "rgb(0,0,255)";
function calc(){
total += 1;
rand1 = Math.random();
rand2 = Math.random();
if(rand1 * rand1 + rand2 * rand2 < 1.0){
inner += 1;
}
context.fillRect(rand1*400,rand2*400,2,2);
val.text("Pi = " + inner * 4.0 / total);
}
setInterval(calc, 2);
code:pi.rb
total = 0
inner = 0
100000.times {
total += 1
rand1 = rand
rand2 = rand
if rand1 * rand1 + rand2 * rand2 < 1.0
inner += 1
end
}
puts inner * 4.0 / total