What is the best way to generate random numbers?
Share
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.
If and only if:
you are not looking for “perfect uniformity” or
you have no C++11 support and not even TR1 (thus you don’t have another choice)
then you might consider using the following C-style solution, which (for the sake of the reputation of this community ~ see rand() Considered Harmful) is written in strike-through font:
Here’s the simple C-style function that generates random number from the interval from
mintomax, inclusive. Those numbers seem to be very close to being uniformly distributed.and don’t forget to call
srandbefore you use it:output:
14253 14481 14210 14029 14289 14503 14235Also have a look at:
Generate a random number within range?
Generate random numbers uniformly over an entire range
and find some time and watch at least first 11 minutes of aforementioned video
Otherwise:
use
<random>just like it was pointed out by Kerrek SB already.