vendredi 30 décembre 2016

Monte Carlo pi method with fixed x

In all Monte Carlo example codes I have found which calculate pi, both x and y are generated randomly between 0 and 1. For example, an example code looks like

  Ran rdm(time(NULL));
  double x, y;
  int sum=0;
  for(int i=0;i<N;i++)
  {
    x=rdm.doub();         // Both x and y are generated randomly
    y=rdm.doub();
    if(x*x+y*y<1)
      sum++;
  }
  return 4.*sum/N;

I don't understand what is the point to randomly generate both axis rather than choose a fixed and uniform x list and then only generate y randomly, like an example code below.

  Ran rdm(time(NULL));
  double x=0.5/N, dx=1./N, y;   //x is a fixed sequential list
  int sum=0;
  for(int i=0;i<N;i++)
  {
    y=rdm.doub();               // only y is generated randomly
    if(x*x+y*y<1)
      sum++;
    x+=dx;
  }
  return 4.*sum/N;

I tried both examples. Both methods converge with speed ~ 1/sqrt(N). The error of the second method is slightly smaller and the second code runs slightly faster. So it seems to me that the second method is better. And for sampling in higher dimension space, I think one can always pick a fixed list in one dimension and randomly sampling in other dimensions. Is this true?

Is there any reference that can prove the fixed x method is also correct?

If the fixed x method is better, why I have never seen any example code written in this way? Is it related to the adaptive importance sampling?




Aucun commentaire:

Enregistrer un commentaire