0

I want to create fast new random number between 0 and 9. For this modified a code that I found there: Why do I always get the same sequence of random numbers with rand()? and integrated it into a loop

The output I get is

Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1

Instead I would like to get something like:

Random fast seeded: 2
Random fast seeded: 8
Random fast seeded: 4
Random fast seeded: 7
Random fast seeded: 3
Random fast seeded: 1
Random fast seeded: 3
Random fast seeded: 5
Random fast seeded: 1
Random fast seeded: 9

Here is the code


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


int main ()
{
  struct timespec ts;
  for (int i = 0; i<10; i++){
    clock_gettime(CLOCK_MONOTONIC, &ts);
    srand((unsigned int)ts.tv_nsec);
    printf ("Random fast seeded: %d\n", rand()%10);
  }
  return 0;
}

What am I doing wrong?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
ecjb
  • 5,169
  • 12
  • 43
  • 79
  • 1
    Call `srand((unsigned)time(NULL));` only once at the very beginning. – David Ranieri May 22 '23 at 21:07
  • What are you doing wrong? You confuse resetting the sequence with obtaining a random value. It's *one call* to obtain a random value - not three. – Weather Vane May 22 '23 at 21:14
  • 1
    @DavidRanieri: Because `srand` is declared `void srand(unsigned int seed)`, an argument passed to it will automatically be converted to `unsigned int` if it satisfies the relevant constraints, and the only function of a cast to `(unsigned)` is to potentially suppress warnings that might indicate an error. E.g., if `time` had been mistyped as some function that returned a pointer, there would be a diagnostic message without the cast but possibly not with it. For that reason, unnecessary casts should be avoided. – Eric Postpischil May 22 '23 at 23:16

1 Answers1

1

Place these two statements

clock_gettime(CLOCK_MONOTONIC, &ts);
srand((unsigned int)ts.tv_nsec);

before the for loop.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335