/* University College London Dept of P&A Course in C++ 3C59 | all rights reserved 1999 | | Utility: Implementation of methods of a class to generate | different types of random numbers | | | Author: P.Clarke */ #include #include #include "RanGen.h" // Needed due to limitations os SIDE 3.1 compiler //typedef int bool; //#define false 0 ; //#define true 1 ; //------------------------ // Method to generate a uniformly distributed random number in [0,1] float RanGen::uniform( ) { int ran ; float x ; // Use library function to get a number in [0, RAND_MAX] ran = rand() ; //Scale to [0,1] and make it a float x = float(ran)/float(RAND_MAX) ; return x ; } //------------------------ // Method to generate a normally distributed random number based upon // a gaussian distribution with mean=0 and standard deviation=1 // // Note: The distribution is curtailed at +-5 sigma for speed float RanGen::gauss( ) { bool notdone = true ; float x, y, g ; while( notdone ) { // Generate a random x value in range in [-5,+5] x = (this->uniform() * 10.0 ) - 5.0 ; //Calc the gaussian function at at x (unormalised) g = exp( - x*x / 2.0 ) ; //Generate a random number in the range [0,max(gaussian)] //Since we havnt normalised the gaussian its max=1 at x=0 y = this->uniform() * 1.0 ; //Test if y < g //If it is then we keep this value of x and so can stop, //otherwise continue in the loop if( y < g ) notdone = false ; } return x ; }