Obtaining double precision random number?

O

osmium

Ronny Mandal said:
Is there a function that will do this task properly?

Not in the standard libraries. If you want numbers in the range 0..1.0
there is a lot of guidance on the Web as to how to produce such numbers from
the integer returned by rand().
 
E

Eric Sosman

Ronny said:
Is there a function that will do this task properly?

("This task" is to obtain a "double precision random number."
For future reference, it's a good idea to put your question in
the body of the message, even if it's the same as the Subject.)

The C library has no function to do this. However, it provides
the tools you need to do it yourself, in at least two ways:

/* Method 1 (simple and sloppy) */
#include <stdlib.h>
...
double r = rand() / (RAND_MAX + 1.0);

This sets `r' to a `double' value between zero (inclusive) and
one (exclusive, almost certainly). However, even though `r' is a
`double' it is probably not "double precision." rand() can produce
at most RAND_MAX+1 different values and RAND_MAX can be as small as
32767, so `r' could have as little as fifteen bits of "precision."
To get finer "grain" in the result you need to combine several rand()
values:

/* Method 2 (more involved, more "precise") */
#include <stdlib.h>
#include <float.h>
...
double r = 0.0;
double s = 1.0;
do {
s /= RAND_MAX + 1.0;
r += rand() * s;
} while (s > DBL_EPSILON);

Roughly speaking, this method builds `r' as a fraction in the
base RAND_MAX+1, with each rand() contributing a new "digit." The
loop continues tacking on "digits" until their significance becomes
too small to matter (DBL_EPSILON is the difference between 1.0 and
the smallest `double' value larger than 1.0; it is the "grain size"
of `double').

HOWEVER, method 2 is not suitable for "high-precision" work
because the guarantees on the quality of rand() itself are too weak.
The method forms `r' from N successive rand() values (two to four
on many machines), and many pseudo-random generators suffer from
accuracy problems when viewed as sources of N-tuples for N>1 (Google
"spectral test" for more information). If you really need "double
precision," you should probably use something other than the generic
rand() as a source of random bits; http://random.mat.sbg.ac.at/news
is a good place to start searching.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top