Pi becslése a valószínűségszámítás segítségével

Eredetileg a js.do oldalon készült, a JavaScriptet gyakoroltam vele. A script a pi értékére ad becslést a leírt módon.

<canvas id=”base” height=”400″ width=”400″ style=”border:1px solid black; float:left;”>
</canvas>

<p id=”desc” style=”font-family:Courier; font-size:12px”>
“PI-darts”<br><br>
This application estimates the value of PI by shooting darts randomly into the area. The probability of a dart landing in a certain part is equal to the rate of their areas compared to the whole (“In”+”Out”). Therefore, using more and more darts, the rate of them hitting the “In” zone will converge to the appropriate probability. Counting how many darts hit “In” and dividing it by the number of all shot darts will get us this rate value.<br><br>
Geometrically, the area of the quarter-circle (“In”) is calculated as R^2*PI/4 (where R is its radius) and the area of a square (“In”+”Out”) is calculated as R^2. Dividing the former with the latter we get PI/4. Thus: <br><br>
PI=4*In/(In+Out)<br><br>
In the formula “In” and “Out” are areas. But according to the first paragraph, we can insert the number of darts that hit those areas and by doing so the result will converge to PI. The more darts we use, the more accurate result we get.<br>
Hit the “Shoot” button to try this method.
</p>
<button type=”button” onclick=”shootThem()”>Shoot!</button>
<button type=”button” onclick=”clearS()”>Clear the table!</button>

<script>

var aCanvas=document.getElementById(“base”);
var context=aCanvas.getContext(“2d”);

function drawArc()
{
context.beginPath();
context.lineWidth=”1″;
context.arc(0,0,400,0,0.5*Math.PI);
context.strokeStyle=”blue”;
context.stroke();
context.font=”bold 18px courier”;
context.fillStyle=”red”;
context.fillText(“In”,160,170);
context.fillStyle=”green”;
context.fillText(“Out”,320,350);
}

function clearS()
{
aCanvas.width=aCanvas.width;
drawArc();
}

function shootThem()
{
dartNum=prompt(“Please give the number of darts to be shot: “,”47538″);
dartOut=0;
dartIn=0;

for (i=1; i<=dartNum; i++)
{
x=Math.random()*aCanvas.width;
y=Math.random()*aCanvas.height;
r=Math.sqrt(x*x+y*y);
fi=Math.atan(y/x);

if (r<400)
{
context.fillStyle=”red”;
dartIn++;
}

else if (r>400)
{
context.fillStyle=”green”;
dartOut++;
}

else
{
if (fi>=Math.PI/4)
{
context.fillStyle=”red”;
dartIn++;
}
else
{
context.fillStyle=”green”;
dartOut++;
}
}
context.fillRect(Math.round(x),Math.round(y),1,1);
}
var piValue=4*dartIn/(dartIn+dartOut);

alert(“In: “+dartIn+”, Out: “+dartOut+”. Estimated value of PI shooting “+dartNum+” darts: “+piValue.toFixed(7));

}

drawArc();

</script>