modifying min/max for param_type in a distribution
Jul 28, 2017 at 1:35pm UTC
How can I modify the minimum and maximum for the range, that was used during construction of a uniform distribution?
I get a compile error with the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include <iostream>
#include <random>
int round_to_hundred(int d) {
// return ((d % 100) < 50) ? d - (d % 100) : d + (100 - (d % 100));
return (d + 50) / 100 * 100;
}
int main() {
int start{300}, end{2000};
std::random_device rd; // obtain a random number from hardware
std::mt19937 eng(rd()); // seed the generator
std::uniform_int_distribution<>::param_type pt(start, end);
std::uniform_int_distribution<> distr(pt); // define the range
std::cout << "start " << distr.a() << " end " << distr.b() << "\n" ;
std::cout << "min " << distr.min() << " max " << distr.max() << "\n" ;
std::cout << "Sample Values: " << distr(eng) << ',' << distr(eng) << ',' << distr(eng) << ',' << distr(eng) << std::endl;
int n {distr(eng)};
std::cout << n << " " << ((n + 50) / 100 * 100) << "\n" ; // round to nearest hundred
start = 1; end = 100;
pt.min(start);
pt.max(end);
std::cout << "Sample Values: " << distr(eng) << ',' << distr(eng) << ',' << distr(eng) << ',' << distr(eng) << std::endl;
n = distr(eng);
std::cout << n << " " << ((n + 5) / 10 * 10) << "\n" ; // round to nearest ten
return 0;
}
Jul 28, 2017 at 2:19pm UTC
Partially solved by constructing a new parameter type, with the new range.
In addition, since the default parameter type still applies to the distribution, one has to override the default with the new param_type by explicitly passing it, as in line 21 & 22.
So this is a working version, but not ideal:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <iostream>
#include <random>
int main() {
int start{300}, end{2000};
std::random_device rd; // obtain a random number from hardware
std::mt19937 eng(rd()); // seed the generator
std::uniform_int_distribution<>::param_type pt(start, end);
std::uniform_int_distribution<> distr(pt); // define the range
std::cout << "start " << distr.min() << " end " << distr.max() << "\n" ;
std::cout << "Sample Values: " << distr(eng) << ',' << distr(eng) << "\n" ;
int n {distr(eng)};
std::cout << n << " rounded to nearest 100 " << ((n + 50) / 100 * 100) << "\n" ; // round to nearest hundred
start = 1; end = 100;
std::uniform_int_distribution<>::param_type pt2(start, end);
std::cout << "Sample Values: " << distr(eng, pt2) << ',' << distr(eng, pt2) << "\n" ;
n = distr(eng, pt2);
std::cout << n << " rounded to nearest 10 " << ((n + 5) / 10 * 10) << "\n" ; // round to nearest ten
return 0;
}
Can anybody suggest a better way ?
Last edited on Jul 28, 2017 at 2:20pm UTC
Topic archived. No new replies allowed.