mardi 23 mai 2017

How to generate random floating point numbes from 0 to 1

I have found a code in this answer How to generate a random number from within a range a code that works perfectyly,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;
  }




Aucun commentaire:

Enregistrer un commentaire