- Dart
Select your favorite languages :
- Or search :
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.
- C
- Clojure
- C++
- C#
- D
- Elixir
- Elixir
- Erlang
- Fortran
- Go
- Haskell
- Haskell
- JS
- JS
- Java
- Java
- Java
- Kotlin
- Lisp
- Lua
- Obj-C
- PHP
- Pascal
- Perl
- Python
- Ruby
- Rust
- Scala
- Scheme
- Smalltalk
- VB
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
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.
programming-idioms.org