1

When I used rand() with srand() to generate random number in [0,1], it gave me numbers like: 0.70324, 0.70328, 0.70321...

They were difference only in the last one or two digits, while I was intended to get random float numbers like 0.1,0.7,0.3....

How could I get random float number like that instead of making difference in the last digit?

Here's my code:

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main(){
    int i;
    float randomNum;
    for (  i=0; i<10; i++){
        srand((unsigned int)time(NULL));
        randomNum = ((float)rand())/RAND_MAX;
        printf("%f\n",randomNum);
     }
    return 0;
}
phuclv
  • 37,963
  • 15
  • 156
  • 475
NUO
  • 247
  • 2
  • 3
  • 14
  • 8
    Move `srand` outside the loop. Call it once, at the start of a program. You keep resetting the RNG, with one second granularity. – Weather Vane Apr 20 '16 at 19:11
  • 1
    Side note: Rarely have I seen the need for the range `[0.0 to 1.0]`, but the range `[0.0 1.0)` (Upper end does not include 1.0) – chux - Reinstate Monica Apr 20 '16 at 19:53
  • 1
    Note: with typical 32-bit `int` and 32-bit `float`, `((float)rand())/RAND_MAX;` will not provide an equal occurrence of `float` values. `1.0f` will occur 64 times as often as `0.0f` due to rounding of `(float)rand()` – chux - Reinstate Monica Apr 20 '16 at 20:26
  • Does this answer your question? [srand() — why call it only once?](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once) – phuclv Apr 21 '21 at 09:59

3 Answers3

8

You should call srand() only once, at the beginning of your program. Calling it before each call to rand() only makes the results more predictable, since each time you call it with a number probably very similar to the previous one.

trent
  • 25,033
  • 7
  • 51
  • 90
2

Move the line

srand((unsigned int)time(NULL));

to the start of the program i.e. just after main.

You only need to seed the random number generator once.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127
2

srand() only initializes the pseudo-random number generator using a piece of data given to it, called the seed. The rand() function then uses this seed to produce random numbers. Afterwards, each call to rand() is based on the previous random number that was generated. You are not intended to call srand() more than once anyway. (You can actually see this behavior in one of rand's implementation)

The problem here is that time() gives you the current time in seconds, so when you initialize the generator and call rand() every time you will get the same number, until one second will pass.

Tomer
  • 3,149
  • 23
  • 26