Logo

Programming-Idioms

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

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 "math/rand/v2"
func pick(a, b  float64)  float64 {
	return a + (rand.Float64() * (b-a))
}

Note that the package math/rand is not crypto-secure.
#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