Calculate Pi with Monte-Carlo-method: Difference between revisions
From JSXGraph Wiki
No edit summary |
No edit summary |
||
Line 22: | Line 22: | ||
} | } | ||
board2.unsuspendUpdate(); | board2.unsuspendUpdate(); | ||
var tin = 0; | |||
var tout = 0; | |||
function updText() { | function updText() { | ||
Line 39: | Line 42: | ||
} | } | ||
text += 'In: ' + inp + ', out: ' + outp + ', total: ' + (inp+outp) + '; ratio: ' + (inp/(inp+outp)) + ', ratio*4: ' + (4*inp/(inp+outp)); | tin += inp; | ||
tout += out; | |||
text += 'In: ' + inp + ', out: ' + outp + ', total: ' + (inp+outp) + '; ratio: ' + (inp/(inp+outp)) + ', ratio*4: ' + (4*inp/(inp+outp)) + '.<br /><b><u>Total</u></b><br/>In: ' + tin + ', out: ' + tout + ', total: ' + (tin+tout) + '; ratio: ' + (tin/(tin+tout)) + ', ratio*4: ' + (4*tin/(tin+tout)); | |||
$('resulttext').innerHTML = text; | $('resulttext').innerHTML = text; | ||
} | } |
Revision as of 09:29, 7 July 2009
Here, at construction time each point receives a function pair as coordinates. In each update these functions which return Math.random() are called. Thus in each update each point receives new random coordinates. The 50 points are updated on the onmousemove event.
This can be used to calculate [math]\displaystyle{ \pi }[/math] using statistics. After each update we count the number of points inside the circle (with midpoint [0,0] and radius 1) and outside the circle. The points are restricted to the square with midpoint [0,0] and edges of length 2.
Please, move the mouse pointer over this area:
<div id="jxgbox" class="jxgbox" style="width:400px; height:400px;" onmousemove="board2.update()"></div>
board2 = JXG.JSXGraph.initBoard('jxgbox', {originX: 10, originY:390 , unitX:380 , unitY: 380});
board2.suspendUpdate();
for (var i=0;i<50;i++) {
var p2 = board2.createElement('point',
[function(){return Math.random();},function(){ return Math.random()}],
{style:5,name:' '});
}
board2.unsuspendUpdate();