Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate random numbers without rand() function?

Tags:

c

random

I want to generate (pseudo) random numbers between 0 and some integer. I don't mind if they aren't too random. I have access to the current time of the day but not the rand function. Can anyone think of a sufficiently robust way to generate these? Perhaps, discarding some bits from time of day and taking modulo my integer or something?

I am using c.

like image 886
AnkurVj Avatar asked Sep 29 '11 20:09

AnkurVj


People also ask

How do you generate a random number in a function?

random() The Math. random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.


1 Answers

If you're after an ultra-simple pseudo-random generator, you can just use a Linear Feedback shift Register.

The wikipedia article has some code snippets for you to look at, but basically the code for a 16-bit generator will look something like this (lightly massaged from that page...)

  unsigned short lfsr = 0xACE1u;   unsigned bit;    unsigned rand()   {     bit  = ((lfsr >> 0) ^ (lfsr >> 2) ^ (lfsr >> 3) ^ (lfsr >> 5) ) & 1;     return lfsr =  (lfsr >> 1) | (bit << 15);   } 
like image 131
Roddy Avatar answered Oct 01 '22 23:10

Roddy