0

I have found a code in this answer How to generate a random integer number from within a range a code that works perfectly, but tis is for integers. Does anybody know how can I change this code so it returns uniformly a number between 0 and 1?

#include <stdlib.h> // For random(), RAND_MAX
// Assumes 0 <= max <= RAND_MAX
// Returns in the closed interval [0, max]
long random_at_most(long max) {
  unsigned long
  // max <= RAND_MAX < ULONG_MAX, so this is okay.
  num_bins = (unsigned long) max + 1,
  num_rand = (unsigned long) RAND_MAX + 1,
  bin_size = num_rand / num_bins,
  defect   = num_rand % num_bins;

  long x;
  do {
    x = random();
  }
  // This is carefully written not to overflow
  while (num_rand - defect <= (unsigned long)x);

  // Truncated division is intentional
  return x/bin_size;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Nikos
  • 17
  • 1
  • 10

2 Answers2

2

You really don't need all that complicated code there. Imagining you initialized your pseudo-random number generator correctly in your main function, with for instance something like this for rand:

srand(time(NULL));

The following code should be enough:

double random(){

    return (double)rand()/RAND_MAX;
}

The idea there is just to pick a random number between 0 and RAND_MAX, and then to divide it by RAND_MAX. As RAND_MAX/RAND_MAX is equal to 1, you will return a random value between 0 and 1.

Izuka
  • 2,572
  • 5
  • 29
  • 34
0

The C way:

    #include <stdlib.h>

    int main(int argc, char** argv)
    {
        printf("Random value: %f\n", (float) rand() / (float) RAND_MAX);
        return 0;
    }

The C++11 way:

    #include <random>

    int main(int argc, char** argv)
    {
        std::default_random_engine generator;
        std::uniform_real_distribution<float> distribution(0.0, 1.0);

        printf("Random value: %f\n", distribution(generator));

        return 0;
    }
dmsovetov
  • 299
  • 1
  • 8