drand48_r - Linux


drand48_r is a C library function that generates uniformly distributed pseudo-random numbers. It is part of the C standard library and is commonly used in simulations, games, and cryptographic applications.


int drand48_r(uint16_t seed16v[3], double *result);


  • seed16v: A pointer to an array of three 16-bit integers representing the seed for the random number generator.
  • result: A pointer to a double variable where the generated random number will be stored.




Simple usage:

#include <stdlib.h>
uint16_t seed16v[3] = { 1, 2, 3 };
double result;

drand48_r(seed16v, &result);
printf("Random number: %f\n", result);

Using a specific seed:

uint16_t seed16v[3] = { 0x1234, 0x5678, 0x9abc };
drand48_r(seed16v, &result);

Common Issues

  • Poor seed values: The seed values should be unpredictable to ensure randomness. Using predictable seeds can lead to non-random results.
  • Seed exhaustion: The drand48_r function uses a 48-bit seed. After generating 2^48 random numbers, the seed will be exhausted and the sequence will repeat.


Combining with rand(3): The drand48_r function generates double-precision random numbers, while rand(3) generates integer random numbers. They can be combined to generate a wider range of random values.


double rand_double() {
  uint16_t seed16v[3];
  double result;

  drand48_r(seed16v, &result);
  return result * RAND_MAX + rand();

Related Commands

  • rand(3): Generates an integer random number.
  • srand48(3) and srand(3): Set the seed for the random number generator.