Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Php

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.

function pick(float $a, float $b): float
{
    $rand = mt_rand() / mt_getrandmax();
    $rand *= ($b - $a);
    $rand += ($a);

    return $rand;
}

Uses PHP7 scalar type hinting and return type declaration. This allows for ints to be passed to the function as well.

Uses mt_rand() instead of rand() for faster generation and uniformity over larger ranges.
#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