I know there is a bit of limitations for a random number generation in C++ (can be non-uniform). How can I generate a number from 1 to 14620?
Thank you.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A common approach is to use
std::rand()with a modulo:However, as @tenfour mentions in his answer, the modulo operator can disrupt the uniformity of values
std::rand()returns. This is because the modulo translates the values it discards into valid values, and this translation might not be uniform. For instance, fornin[0, 10)the valuen % 9translates9to0, so you can get zero by either a true zero or a 9 translated to zero. The other values have each only one chance to yield.An alternative approach is to translate the random number from
std::rand()to a floating-point value in the range[0, 1)and then translate and shift the value to within the range you desire.