It seems that your immediate problem has been resolved, but I think another point is worth mentioning. Using the remainder to fix outputs from rand to a given range usually results in biased results. Specifically, if the range of the generator (RAND_MAX in the case of C or C ++) is not a multiple of the range you are clamping, some outputs will occur more often than others. For comparison, consider trying to split 11 candies evenly between 3 children (without breaking them into pieces). The only way to do this is to NOT hand out some sweets. Similarly, with a random number generator, the only way to get a uniform distribution in your output is not to use some inputs.
int rand_lim(int limit) { int divisor = RAND_MAX/(limit+1); int retval; do { retval = rand() / divisor; } while (retval > limit); return retval; }
As Aveikau noted in his post, you usually want to use the upper bits from a typical linear congruent generator. The lower bits are usually more predictable. Dividing, instead of taking the remainder, saves the upper bits. Although this has a while loop, it is often executed only once and rarely more than twice, so its impact on performance is pretty minimal.
Regardless of whether itโs worth it, it depends on what kind of use you create from the number you create - if you want to play dice or cards for the game that your children will play a couple of times, using the rest, as a rule, it will hurt a thing. If you are trying to do some kind of Monte Carlo simulation (for example), you probably want to be a little more careful though ...
Jerry Coffin Jan 25 2018-10-25T00: 00Z
source share