3.9 Using Random Numbers

Ptolemy uses the Gnu library routines for the random number generation. Refer to Volume II of the Art of Computer Programming by Knuth for details about the method. There are built-in classes for some popular distributions: uniform, exponential, geometric, discrete uniform, normal, log-normal, and so on. These classes use a common basic random number generation routine which is realized in the `ACG` class. Here are some examples of using random numbers.

hinclude { <NegExp.h> }
ccinclude { <ACG.h> }
protected {
NegativeExpntl *random;
}
// declare the static random-number generator in the .cc file
code {
extern ACG* gen;
}
constructor {
random = NULL;
}
destructor {
if(random) delete random;
}
setup {
if(random) delete random;
random = new NegativeExpntl(double(meanTime),gen);
DERepeatStar :: setup();
}
go {
......
// Generate an exponential random variable.
double p = (*random)();
......
}
The built-in class for an exponentially distributed random numbers is `NegativeExpntl`.

hinclude { <Uniform.h> }
ccinclude { <ACG.h> }
protected {
Uniform *random;
}
// declare the extern random-number generator in the .cc file
code {
extern ACG* gen;
}
constructor {
random = NULL;
}
destructor {
if(random) delete random;
}
setup {
if(random) delete random;
random = new Uniform(0,double(output.numberPorts()),gen);
}
go {
......
double p = (*random)();
......
}
You may notice that the two examples above are very similar in nature. You can get another kind of distribution for the random numbers, by including the appropriate library file in the `.h` file and by creating the instance with the right parameters in the `setup` method.

Copyright © 1990-1997, University of California. All rights reserved.