generating random double between x and y??
Apr 27, 2020 at 7:43pm UTC
Hi ! I'm just so confused with how to generate the random double ranging between 'lower' and upper. My code is out of the range I set up. Please let me know which part should be fixed! thank you
1 2 3 4 5
int = lower, upper;
cin>> lower >> upper;
srand(time(NULL));
double rand_number2 = (rand() / (double )RAND_MAX * upper) + lower;
Apr 27, 2020 at 7:51pm UTC
If you must use rand() then maybe something like this:
double r = (rand() / (double )RAND_MAX) * (upper - lower) + lower;
Or using the C++ random library.
1 2 3 4
std::default_random_engine rnd{std::random_device{}()};
std::uniform_real_distribution<double > dist(lower, upper);
double r = dist(rnd);
Last edited on Apr 27, 2020 at 7:51pm UTC
Apr 27, 2020 at 8:20pm UTC
Line 2 is invalid. int lower, upper;
Apr 27, 2020 at 9:31pm UTC
Thank you guys!!
Topic archived. No new replies allowed.