0

I have a program where I use drand48 and many parts of the program. The program requirement is such that you need the program to generate the same numbers each time, except for one part where i need to have the program generate different numbers in different runs.

Now if I use srand(time(NULL)) at the beginning of the program (as suggested in many forums), I end up changing all the numbers when I run the program multiple times.

If I use srand(time(NULL)) inside the relevant loop where I want the change to take place (across program runs), nothing happens and there is no change of random numbers.

Is there a solution to this ???

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
timur
  • 1

3 Answers3

0

The C libraries support various different random number generators.

drand48() belongs to a family of functions that generate 48-bit pseudorandom values based on the formula rn+1 = (a ยท rn + c) mod m, where a = 0xfdeece66d, c = 0xb, and m = 248. To set a new random seed for these functions, you have to use either srand48() or seed48().

srand() won't have any effect on these functions because it belongs to a different system of calls that includes rand(). But this means you can continue to use drand48() in places where you want your random numbers to be repeatable, and srand()/rand() in places where you want the random numbers to be different each time.

r3mainer
  • 23,981
  • 3
  • 51
  • 88
0

If you are using a GNU system, you can use the [drand48_r()][1] interface to achieve this.

__thread struct drand48_data drand48_same_buffer;
double drand48_same () {
    double x;
    drand48_r(&drand48_same_buffer, &x);
    return x;
}

I used the __thread GCC extension to create a per-thread instance of the random number state buffer.

jxh
  • 69,070
  • 8
  • 110
  • 193
0

If you want to tune the parameters of the underlying generator, follow jxh's advice; if you're happy with just a different seed, simply use drand48's cousin, erand48.

EDIT: are you using the bionic libc? because the discussion at Undefined reference error - rand revealed that bionic's rand() is just a wrapper around drand48 and friends (bug,bug,bug!)

Community
  • 1
  • 1
loreb
  • 1,327
  • 1
  • 7
  • 6