Top Up Prev Next Bottom Contents Index Search

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.

The first example is the part of the DE Poisson star. See the DE chapter for details on how to write DE stars.


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.

The Ptolemy kernel provides a single object to generate a stream of random numbers; the global variable gen (a poor choice of name, perhaps) is a pointer to it. We create an instance of the NegativeExpntl class in the setup method, not in the constructor since Ptolemy allows you to change the seed of the random number generator. When the user changes the seed of the random number generator, the object pointed to by gen is deleted and re-created, so all objects such as the one pointed to by random in this star become invalid.

Finally, we can read a random number of the specific type by calling operator () of the NegativeExpnl class.

This example uses a uniformly distributed random number.


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.



Top Up Prev Next Bottom Contents Index Search

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