Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c - random number generator

Tags:

c

random

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

like image 692
tm1 Avatar asked Mar 07 '10 14:03

tm1


People also ask

What does RAND () do in C?

rand() The function rand() is used to generate the pseudo random number. It returns an integer value and its range is from 0 to rand_max i.e 32767.

What is the range of rand () in C?

The rand function, declared in stdlib. h, returns a random integer in the range 0 to RAND_MAX (inclusive) every time you call it. On machines using the GNU C library RAND_MAX is equal to INT_MAX or 231-1, but it may be as small as 32767.


2 Answers

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

double random_number = rand() / (double)RAND_MAX;
like image 141
Mark Elliot Avatar answered Oct 01 '22 08:10

Mark Elliot


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

like image 42
qrdl Avatar answered Oct 01 '22 09:10

qrdl