Normal(Gaussian) Distribution Function in C++

前端 未结 3 2035
遥遥无期
遥遥无期 2021-01-28 21:00

I need to know a way to have the Gaussian Distribution of 50 numbers. I know of the Boost library, which generates random numbers. In my case, I don\'t need random numbers; I ne

3条回答
  •  清酒与你
    2021-01-28 21:55

    I think the OP was asking for a random number generator, in which the random numbers are not uniformly distributed (as is typical e.g. rand() in C) but are Gaussian distributed.

    This short routine adapted from "Numerical Recipes in C" (Press et al, 1992) may be of use:

    double grand() {
    
      double r,v1,v2,fac;
    
      r=2;
      while (r>=1) {
        v1=(2*((double)rand()/(double)RAND_MAX)-1);
        v2=(2*((double)rand()/(double)RAND_MAX)-1);
        r=v1*v1+v2*v2;
      }
      fac=sqrt(-2*log(r)/r);
    
      return(v2*fac);
    
    }
    

    ...ensure the relevant #includes are present for the math functions and rand, and that srand(time(NULL)) or similar has been called to appropriately seed the C rand() RNG.

提交回复
热议问题