Re: question about random generator
- From: Eric Sosman <esosman@xxxxxxxxxxxxxxxxxxx>
- Date: Mon, 25 Jul 2005 21:14:04 -0400
Marc Dansereau wrote:
Hi all
I am new to this forum and to the c programming language. If I understand, the random() function in C return numbers that follow a uniform distribution U(0,1). Can somebody know how to generate a set of random number that follow a normal distribution N(0,1) ? I am develloping on power4 machine running AIX.
First, there is no random() function in the Standard C library. If your system offers such a function, it is an extra, bonus, add-on extension to C, not part of C itself.
The rand() function generates uniformly distributed integers in the range 0 <= rand() <= RAND_MAX <= 32767. From this source, you can generate floating-point numbers in the range 0 <= y < 1: `rand() / (RAND_MAX + 1.0)'. Note that these values may have as little as fifteen bits' "precision;" if you need more, you may need to combine the results of multiple rand() calls as in
(rand() + (rand() / (RAND_MAX + 1.0))) / (RAND_MAX + 1.0)
(Pedants take note: The ambiguity in the above expression may be considered a benefit, under the circumstances.)
Now that you've got a source of (approximately) uniformly- distributed numbers in [0,1), there are several ways to produce normally-distributed numbers. The easiest to program is surely the "polar method" (Google is your friend); faster methods exist if you're willing to do the extra work. See Knuth "The Art of Computer Programming, Volume II: Seminumerical Algorithms." (In fact, see Knuth anyhow: the Standard makes almost no guarantees about the statistical "goodness" of the rand() function, and if you're doing high-precision work you should substitute a source whose characteristics you can count on.)
-- Eric Sosman esosman@xxxxxxxxxxxxxxxxxxx .
- Follow-Ups:
- Re: question about random generator
- From: Peter Nilsson
- Re: question about random generator
- References:
- question about random generator
- From: Marc Dansereau
- question about random generator
- Prev by Date: Re: question about random generator
- Next by Date: Re: question about random generator
- Previous by thread: Re: question about random generator
- Next by thread: Re: question about random generator
- Index(es):
Relevant Pages
|