I am creating a c++ class which randomly puts a number of particles on a lattice and then lets those particles jump on the lattice in a random fashion. I have managed to implement this, but using the random number generators rand(), which I understand is not a very good idea.. Now I want to rewrite my code using Ran in the numerical recipes package for c++ in order to get random numbers in the range 0 to 1. My problem is that I want to use the random number generator "globally" in all member functions in the class (for instance, in one member function, setInit(), which initially puts the particles on the lattice and in one member function, Jump(), which I use repeatedly and which obtains the random jumps of the particles). Also, I would be preferable (but not necessary) if it would be possible to first define a Ran object, and AFTERWARDS seed this object [like one does with rand() and srand()], but as I understand it one must seed the Ran object at the same instant it is defined? When I define a random number generator as below in a main program it works fine:

main() {

double r;
int seed;
seed=(int) (time(NULL));
cout<<"random seed="<<seed<<endl;
Ran NRrand(seed);
for (int i=1; i<=10; i++) {

but I have NO idea how define it in my class - I call repeatedly the function Jump() and I cannot therefore define a NRrand (see code above) in the function Jump(), because then a new NRrand would be initiated each time I call that function (and therefore give the same random number). Anyone has an idea how to solve this problem???? Thanks!

10 Years
Discussion Span
Last Post by Ancient Dragon

>>but using the random number generators rand(), which I understand is not a very good idea
why not ?

>>but I have NO idea how define it in my class
declare it as static and there will only be one instance of it for all instances of your class.


many thanks, works now!
ps. the built-in random number generator rand() is according to the book "Numerical Recipes - the art of scientific computing" not recommended for serious scientific computing.


That's probably true for serious scientific computing. If that's the kind of program you are writing then you are correct not to use it. But for most other kinds of programming its as good as any other.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.