Logo

Programming-Idioms

  • Elixir
  • D

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.

import std.random
real pick(real _a, real _b){
    return uniform(_a, _b);
}

This is in the standard library. Use uniform(start, end) to get a number between start and end.
a + :rand.uniform() * (b-a)
defmodule MyRandomPicker do
  def pick(a, b), do: a + (b - a) * :rand.uniform()
end

this makes use of Erlang's rand module
#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