get random number in range [-2..19]

Apr 6, 2020 at 7:02pm
can you recommend better way to generate random number within the range
[-2..19]:
Apr 6, 2020 at 7:08pm
Better than what?

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <random>

int main()
{
    std::default_random_engine rnd {std::random_device{}()};
    std::uniform_int_distribution<int> dist(-2, 19);

    for (int i = 0; i < 10; ++i)
        std::cout << dist(rnd) << '\n';
}

Last edited on Apr 6, 2020 at 7:10pm
Apr 6, 2020 at 7:10pm
like the best way to..
Apr 6, 2020 at 7:14pm
Best way would be to get your own source of a radioactive isotope and measure the decay of the element, then do some math to linearize the Gaussian curve (maybe a mathematician can help here).
Second best way is dutch's post (assuming your compiler supports random_device).
Last edited on Apr 6, 2020 at 7:15pm
Apr 6, 2020 at 10:04pm
"the best way..." is very subjective. Do you want to generate random numbers in C or C++?

dutch has one of the better ways to generate random numbers if the implementation supports std::random_device. A viable work-around is to generate a seed sequence using std::random_device and the system clock.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <chrono>
#include <random>

int main()
{
   std::seed_seq::result_type seeds[] { std::random_device {}(),
                                        std::seed_seq::result_type(std::chrono::system_clock::now().time_since_epoch().count()) };
   static std::seed_seq sseq(std::begin(seeds), std::end(seeds));

   std::default_random_engine rng(sseq);

   std::uniform_int_distribution<int> dist(-2, 19);

   // code to use what you've just instantiated.
}
Topic archived. No new replies allowed.