Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I always get the same sequence of random numbers with rand()?

Tags:

c

random

This is the first time I'm trying random numbers with C (I miss C#). Here is my code:

int i, j = 0; for(i = 0; i <= 10; i++) {     j = rand();     printf("j = %d\n", j); } 

with this code, I get the same sequence every time I run the code. But it generates different random sequences if I add srand(/*somevalue/*) before the for loop. Can anyone explain why?

like image 215
Hannoun Yassir Avatar asked Jul 10 '09 10:07

Hannoun Yassir


People also ask

Why is rand () giving me the same number?

Code. In the code below, the rand() function is used without seeding. Therefore, every time you press the run button, ​it generates the same number.

Why is Rand not random in C?

In the C language, the rand() function is used for Pseudo Number Generator(PRNG). The random numbers generated by the rand() function are not truly random. It is a sequence that repeats periodically, but the period is so large that we can ignore it.

Is Rand function truly random?

What that means is that, technically speaking, the numbers that Excel's RAND functions generate aren't truly random. Some companies want to get as random numbers as possible and get creative as to where their random data comes from (like CloudFlare's wall of Lava Lamps).


1 Answers

You have to seed it. Seeding it with the time is a good idea:

srand()

#include <stdio.h> #include <stdlib.h> #include <time.h>  int main () {   srand ( time(NULL) );   printf ("Random Number: %d\n", rand() %100);   return 0; } 

You get the same sequence because rand() is automatically seeded with the a value of 1 if you do not call srand().

Edit

Due to comments

rand() will return a number between 0 and RAND_MAX (defined in the standard library). Using the modulo operator (%) gives the remainder of the division rand() / 100. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand() % 1000.

like image 106
kjfletch Avatar answered Oct 10 '22 14:10

kjfletch