Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Obj-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.

@import GameplayKit;
float pick(float a,float b) {
  id<GKRandom>  rnd=GKMersenneTwisterRandomSource.sharedRandom;
  float ru;
  while ((ru=rnd.nextUniform)==1);
  return a+ru*(b-a);
}

Other sources or a GKRandomDistribution might be better in a particular case; see the linked doc
#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