Programming-Idioms

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

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.

#include <stdlib.h>
double pick(double a, double b)
{
	return a + (double)rand() / ((double)RAND_MAX * (b - a));
}
  (defn rand-between [a b]
    (+ a (* (- b a) (rand))))
#include <random>
float pick(float a, float b)
{
	std::default_random_engine generator;
	std::uniform_real_distribution distribution(a, b);
	return distribution(generator);
}
double RandomDouble(double a, double b)
{
	Random rng=new Random();
 	return rng.Next(a,b);
}
import std.random
real pick(real _a, real _b){
    return uniform(_a, _b);
}
import  'dart:math';
double pick(num a, num b) => a + new Random().nextDouble() * (b - a);
a + :rand.uniform() * (b-a)
defmodule MyRandomPicker do
  def pick(a, b), do: a + (b - a) * :rand.uniform()
end
A + (B - A) * rand:uniform().
call random_number(c)
d = a + (b-a) * c
import "math/rand"
func pick(a, b  float64)  float64 {
	return a + (rand.Float64() * (b-a))
}
pick a b = do
  r <- System.Random.randomIO :: IO Double
  return a + (r * (b - a))
pick(a,b)=
  return.(+a).(*(b-a))=<<System.Random.randomIO::IO(Double)
a + (b-a) * Math.random();
a + Math.random() * (b - a)
import java.util.Math;
double pick(double a, double b){
	return a + (Math.random() * (b-a));
}
function pick(a,b)
	return a + (math.random()*(b-a))
end
@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);
}
function pick(float $a, float $b): float
{
    $rand = mt_rand() / mt_getrandmax();
    $rand *= ($b - $a);
    $rand += ($a);

    return $rand;
}
function pick(a, b:real): real;
begin
  result := a + random * (b - a);
end;
my ($min, $max) = (1.5, 7.2);
my $x = $min + rand($max-$min);
import random
random.uniform(a,b)
import random
def pick(a,b):
    return random.randrange(a, b)
rand(a...b)
extern crate rand;
use rand::{Rng, thread_rng};
thread_rng().gen_range(a, b);
import math.random
def randomDraw(min: Double, max: Double): Double = {
  val range = max - min
  (random.doubleValue * range) + min
}
None
Public Function RandomDouble(a As Double, b As Double) As Double
    Dim rng As New Random
    Return rng.Next(a, b)
End Function

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms