Logo

Programming-Idioms

  • Rust
  • C++

Idiom #14 Pick uniformly a random floating point number in [a..b)

Pick a random number greater than or equals to a, strictly inferior to b. Precondition : a < b.

#include <random>
float pick(float a, float b)
{
	std::default_random_engine generator;
	std::uniform_real_distribution distribution(a, b);
	return distribution(generator);
}

You probably want to pass a random engine into the function instead of creating a new one each time in generator.

This example doesn't seed the generator, so will generate the same result in every call.
extern crate rand;
use rand::{Rng, thread_rng};
thread_rng().gen_range(a..b);

If you need to generate a lot of random stuff, save the thread_rng as a variable so it is only initialized once.
#include <stdlib.h>
double pick(double a, double b)
{
	return a + (double)rand() / ((double)RAND_MAX * (b - a));
}

this is not uniformly distributed!!

New implementation...
< >
programming-idioms.org