Many random-number generators return floating numbers between 0 and 1.
What’s the best and correct way to get integers between a and b?
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.
Divide the interval [0,1] in B-A+1 bins
Example A=2, B=5
The problem with the formula
is that your Rnd() generation interval is closed on both sides, thus the 0 and the 1 are both possible outputs and the formula gives 6 when the Rnd() is exactly 1.
In a real random distribution (not pseudo), the 1 has probability zero. I think it is safe enough to program something like:
Edit
Just a quick test in Mathematica:
Define our function:
Build a table with 3 10^5 numbers in [1,100]:
Check minimum and maximum:
Lets see the distribution: