I would like to make random numbers in a specific range, like "pick a random number between 18 and 35"? How can I do that with the rand()
function?
相关问题
- Multiple sockets for clients to connect to
- Keeping track of variable instances
- What is the best way to do a search in a large fil
- How to get the maximum of more than 2 numbers in V
- glDrawElements only draws half a quad
in general, if rand() returns a float value in [0.0 ... 1.0) (that is, you may get values arbitrarily close to 1.0 but not actually 1) then you will want something like
Note that this will never actually return the hi value - therefore I have incremented it by 1 (ie, you will get all values from 18 to 35 inclusive, but never 36).
Hope that helps.
Depending on the language you are using, the built in Random number generator may already have this capability - do a bit more research.
Suppose that the random number generator that you have always returns numbers in some given range. Just for the sake of argument, lets say the range is 0..65536 but you want random numbers in the range Low..High, 18..35 in your example.
The wrong way to do it would be something like:
rand() returns a number in range 0..65536. Take the remainder after dividing by (High - Low + 1) which in this example is (35 - 18 + 1 = 18). The result is a number between 0..17. To this you add Low (18) which shifts the result, r, into the range 18..35. The range you are looking for.
Numbers generated this way do not have a uniform distribution in cases where the divisor used to obtain the remainder is not an even multiple of the upper limit returned by the rand() function. See the Fischer Yates Algorithm - Modulo Bias. To remove this bias you need to calculate the largest number that is smaller than what rand() returns but evenly divides by (High - Low + 1). In your case that is 3640 * 18 = 65520. Use this as a high range filter on the numbers returned by rand() as follows:
Now the random numbers you generate should have the same distribution characteristics as rand().
If this is written in C, then you are pretty close. Compiling this code:
And running it in a pipeline produces this output:
The key is you forgot to add 1 -- the fencepost error.
You can generalize this into a function:
assume rand() give you a number between 0 and 1.0
then use rand() * (35 - 18) + 18 to get a random number between 18 and 35.
Edit: you don't need mod for this.