← Back to team overview

yade-users team mailing list archive

Re: [Question #253257]: generate a random number in the C++ code

 

Question #253257 on Yade changed:
https://answers.launchpad.net/yade/+question/253257

Jan Stránský posted a new comment:
Hi Raphael,

to generate random number in the interval 0 to 1, I use

double random() { return (double)rand()/(double)RAND_MAX; }

for normal distribution I use Box-Muller method (see also [1,2])

// function generating normally distributed random numbers using Box-Muller
method
double randNormal (double mean, double stddev, double min=-1e200, double
max=1e200) {
   double r, u, v, c, ret;
   do {
      do {
         u = 2*(double)rand() / (double)RAND_MAX-1;
         v = 2*(double)rand() / (double)RAND_MAX-1;
         r = u*u + v*v;
      } while (r==0. || r>1.);
      c = sqrt(-2*log(r)/r);
      ret = mean + u*c*stddev;
   } while (ret <= min || ret >= max);
   return ret;
}

cheers
Jan

[1] http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform
[2]
http://math60082.blogspot.cz/2013/03/c-coding-random-numbers-and-monte-carlo.html



2014-08-18 19:36 GMT+02:00 Raphaël Maurin <
question253257@xxxxxxxxxxxxxxxxxxxxx>:

> Question #253257 on Yade changed:
> https://answers.launchpad.net/yade/+question/253257
>
> Raphaël Maurin posted a new comment:
> One last thing, the random number generator using
> #include<random>
> std::default_random_engine generator;
> std::normal_distribution<double> distribution(0.0,1.0);
> double number = distribution(generator);
>
> is pretty bad, I am able to see by eyes some number which are repeated
> many times...I don't like it much. Does someone knows a better way to
> generate random numbers in C++ ?
>
> Thanks !
>
> Raphaël
>
> --
> You received this question notification because you are a member of
> yade-users, which is an answer contact for Yade.
>
> _______________________________________________
> Mailing list: https://launchpad.net/~yade-users
> Post to     : yade-users@xxxxxxxxxxxxxxxxxxx
> Unsubscribe : https://launchpad.net/~yade-users
> More help   : https://help.launchpad.net/ListHelp
>

-- 
You received this question notification because you are a member of
yade-users, which is an answer contact for Yade.