tm1
tm1

Reputation: 211

c - random number generator

How do I generate a random number between 0 and 1?

Upvotes: 15

Views: 48547

Answers (3)

ephemient
ephemient

Reputation: 205024

man 3 drand48 is exactly what you asked for.

The drand48() and erand48() functions return non-negative, double-precision, floating-point values, uniformly distributed over the interval [0.0 , 1.0].

These are found in #include <stdlib.h> on UNIX platforms. They're not in ANSI C, though, so (for example) you won't find them on Windows unless you bring your own implementation (e.g. LibGW32C).

Upvotes: 8

qrdl
qrdl

Reputation: 35008

Assuming OP wants either 0 or 1:

srand(time(NULL));
foo = rand() & 1;

Edit inspired by comment: Old rand() implementations had a flaw - lower-order bits had much shorter periods than higher-order bits so use of low-order bit for such implementations isn't good. If you know your rand() implementation suffers from this flaw, use high-order bit, like this:

foo = rand() >> (sizeof(int)*8-1)

assuming regular 8-bits-per-byte architectures

Upvotes: 8

Mark Elliot
Mark Elliot

Reputation: 77104

You can generate a pseudorandom number using stdlib.h. Simply include stdlib, then call

double random_number = rand() / (double)RAND_MAX;

Upvotes: 22

Related Questions