Tell me an algorithm that displays random numbers in the range [a, b]
4 answers
rand() % (b - a + 1) + a
- fiveA more correct option, in my opinion, is
(double)rand() * (ba) / RAND_MAX + a
And even better, it’s better to use not rand (), but better quality RNG. - gecube - what was provided was necessary =) - nullptr
- 2qwerty12359: what was presented works as long as b - a <RAND_MAX (and the distribution is not even). - dzhioev
- I needed exactly small segments that did not outweigh RAND_MAX - nullptr
- 3This method of pruning gives an uneven distribution! - gbg
|
Since the rand
function has been deprecated since C ++ 11 (it has bad characteristics), now it is better to use the classes from <random>
:
#include <random> #include <iostream> int main() { std::random_device random_device; // Источник энтропии. std::mt19937 generator(random_device()); // Генератор случайных чисел. // (Здесь берется одно инициализирующее значение, можно брать больше) std::uniform_int_distribution<> distribution(10, 20); // Равномерное распределение [10, 20] int x = distribution(generator); // Случайное число. std::cout << x << '\n'; }
|
The boost
library also has its own random
boost::random::mt19937 rng; // генерирует случайные значения boost::random::uniform_int_distribution<> six(10,20); // Равномерное распределение [10, 20] int x = six(rng); // Случайное число.
|
Ready example:
int random (int min, int max) { max++; return abs(rand()%(max-min))+min; }
- fourAnd how does this differ from the accepted answer? - VladD
|