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.
- Java
- Java
- Java
- C
- Clojure
- C++
- C#
- D
- Dart
- Elixir
- Elixir
- Erlang
- Fortran
- Go
- Haskell
- Haskell
- JS
- JS
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Perl
- Python
- Ruby
- Rust
- Scala
- Scheme
- Smalltalk
- VB
(defn rand-between [a b]
(+ a (* (- b a) (rand))))
float pick(float a, float b)
{
std::default_random_engine generator;
std::uniform_real_distribution distribution(a, b);
return distribution(generator);
}
You probably want to pass a random engine into the function instead of creating a new one each time in generator.
This example doesn't seed the generator, so will generate the same result in every call.
This example doesn't seed the generator, so will generate the same result in every call.
real pick(real _a, real _b){
return uniform(_a, _b);
}
This is in the standard library. Use uniform(start, end) to get a number between start and end.
defmodule MyRandomPicker do
def pick(a, b), do: a + (b - a) * :rand.uniform()
end
this makes use of Erlang's rand module
a + :rand.uniform() * (b-a)
call random_number(c)
d = a + (b-a) * c
c is a temporary variable in [0:1[.
pick(a,b)=
return.(+a).(*(b-a))=<<System.Random.randomIO::IO(Double)
pick a b = do
r <- System.Random.randomIO :: IO Double
return a + (r * (b - a))
a + Math.random() * (b - a)
a + (b-a) * Math.random();
(+ a (random (float (- b a))))
function pick(a,b)
return a + (math.random()*(b-a))
end
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
function pick(float $a, float $b): float
{
$rand = mt_rand() / mt_getrandmax();
$rand *= ($b - $a);
$rand += ($a);
return $rand;
}
Uses PHP7 scalar type hinting and return type declaration. This allows for ints to be passed to the function as well.
Uses mt_rand() instead of rand() for faster generation and uniformity over larger ranges.
Uses mt_rand() instead of rand() for faster generation and uniformity over larger ranges.
function pick(a, b:real): real;
begin
result := a + random * (b - a);
end;
real can be exchanged with, or set to any other float type like
single, double, extended ...
single, double, extended ...
my ($min, $max) = (1.5, 7.2);
my $x = $min + rand($max-$min);
rand(a...b)
(Presuming a and/or b are floats) a range constructed using ... excludes the end value.
(+ a (* (- b a) (random 1.0)))
Tested with Chez Scheme
| rand |
rand := Random new.
rand next * (b - a) + a