Message-ID: <3211A6BE.1E32@pobox.oleane.com> Date: Wed, 14 Aug 1996 12:13:18 +0200 From: Francois Charton Organization: CCMSA MIME-Version: 1.0 To: djgpp AT delorie DOT com Subject: Re: rand(), random') or libg++ Random? Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit stwand07 AT uctvms DOT uct DOT ac DOT za wrote: > I am busy working on an optimisation program that makes extensive use of random > number (stochastic search). I have been using srand(time(NULL)) and rand() to > give random numbers in the range 0..1, which I then scale as required. I have > heard that rand() is not very good, so my questions are : > 1. Is random() any better? > 2. Are the libg++ Random classes better? > > I need a normal distribution with zero mean, so 'better' refers to these > criteria. > random() is definitely better that rand(), albeit slower. Using one or the other depends on what you are doing : -> if you need a large number or statistically random values, for instance when doing MonteCarlo integration, or in studying probabilities or stats, you'd better read a bit on random numbers generators, (I suggest : Numerical Recipes in C, 2nd Ed,(Press et al, Cambridge University Press) and the Art of Computer Programming (D Knuth)). You will find many examples of well tested algorithms, which may "guarantee" good randomness. -> if you just need to put some random factor in your calculation, then rand() is ok. If the optimisation program you are trying to do is something like simulated annealing, or stochastic gradient, rand() should be ok (the quality of the random number generator is not important for the algorithm to work...). However, if you use the random generator to "sample points" in space : that is to find some values where the function you will optimize will be evaluated, I suggest you forget about rand() and random(), and all linear congruentila generator (things the calculate numbers as : next = a * previous + b (modulo c)) : the points they will sample WILL NOT BE randomly distributed in space, (more on that in references). Also note that all of these algorithms give uniform distributions, not normal. To get a normal distribution, you have to transform the output of the random number generator. It can be done as follows (I suppose you want a 1 dimensional normal distribution, if it was multidimensional, read Numerical Recipes, or, better : Devroye : Non-Uniform Random Variable Generation, Springer verlag, 1986) : let x be the random number you got from rand(), calculate y=sqrt(-2log(x)) y follows a normal distribution, which you have to scale to get the variance you want. BTW, it might be what the C++ random class does. I don't know. Regards Francois,