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

From JSXGraph Wiki
(New page: 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...)
 
No edit summary
Line 15: Line 15:
  c = board2.createElement('circle', [[0,0], 1]);
  c = board2.createElement('circle', [[0,0], 1]);
  board2.suspendUpdate();
  board2.suspendUpdate();
var p2 = [];
  for (var i=0;i<50;i++) {
  for (var i=0;i<50;i++) {
   var p2[i] = board2.createElement('point',
   p2[i] = board2.createElement('point',
           [function(){return 2*Math.random()-1;},function(){ return 2*Math.random()-1;}],
           [function(){return 2*Math.random()-1;},function(){ return 2*Math.random()-1;}],
           {style:5,name:' '});
           {style:5,name:' '});
Line 25: Line 26:
   var text = '';
   var text = '';


   var in = 0;
   var inp = 0;
   var out = 0;
   var outp = 0;


   for(var i=0; i<p2.length;i++) {
   for(var i=0; i<p2.length;i++) {
Line 33: Line 34:


     if(x*x+y*y <= 1)
     if(x*x+y*y <= 1)
       in++;
       inp++;
     else
     else
       out++;
       outp++;
   }
   }


   text += 'In: ' + in + ', out: ' + out + ', total: ' + (in+out) + '; ratio: ' + (in/(in+out));
   text += 'In: ' + inp + ', out: ' + outp + ', total: ' + (inp+outp) + '; ratio: ' + (inp/(inp+outp)) + ', ratio*4: ' + (4*inp/(inp+outp));
   $('resulttext').innerHTML = text;
   $('resulttext').innerHTML = text;
  }
  }

Revision as of 09:27, 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();