Calculate Pi with Monte-Carlo-method: Difference between revisions

From JSXGraph Wiki
No edit summary
No edit summary
Line 25: Line 25:
  var tin = 0;
  var tin = 0;
  var tout = 0;
  var tout = 0;
var count = 0;


  function updText() {
  function updText() {
  count++;
   var text = '';
   var text = '';


Line 45: Line 47:
   tout += outp;
   tout += outp;


   text += '<b><u>Current</u></b><br/>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));
   text += '<b><u>Current</u></b><br/>In: ' + inp + ', out: ' + outp + ', total: ' + (inp+outp) + '; ratio: ' + (inp/(inp+outp)) + ', ratio*4: ' + (4*inp/(inp+outp)) + '.<br /><b><u>Total</u></b> (' + count + ' updates in total)<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:32, 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();