Logo

Programming-Idioms

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

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.

Imports System
Function pick(a As Double, b As Double) As Double
    Static rng As New Random()
    Return rng.NextDouble() * (b - a) + a
End Function

Constructor-created Random instances are not thread-safe, but VB.NET implicitly locks around access of static locals.
#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