Logo

Programming-Idioms

Pick a random number greater than or equals to a, strictly inferior to b. Precondition : a < b.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
#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);
}
using System;
Random rng = new();
double pick(double a, double b)
{
    return rng.NextDouble() * (b - a) + a;
}
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 + Math.random() * (b - a)
a + (b-a) * Math.random();
import java.util.Random;
Random random = new Random();
float value = random.nextFloat(a, b);
import java.util.Math;
double pick(double a, double b){
	return a + (Math.random() * (b-a));
}
import java.util.Random;
Random random = new Random();
float value = (random.nextFloat() * (b - a)) + a;
import kotlin.random.Random
Random.nextDouble(a,b)
(+ a (random (float (- 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)
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
}
(+ a (* (- b a) (random 1.0)))


| rand |
rand := Random new.
rand next * (b - a) + a
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