digitalmars.D.learn - random number within a specified range?
- Michael P. (4/4) Oct 05 2008 Hi,
- Jarrett Billingsley (7/11) Oct 05 2008 lo + rand() % (hi - lo)
- Don (12/29) Oct 09 2008 The random numbers will not be evenly distributed, though. You'll get
Hi, How would I go about getting a random number that was in a specified range of 2 numbers? For example, getting a number inbetween 1000 and 2000. -Michael P.
Oct 05 2008
On Sun, Oct 5, 2008 at 7:34 PM, Michael P. <baseball.mjp gmail.com> wrote:Hi, How would I go about getting a random number that was in a specified range of 2 numbers? For example, getting a number inbetween 1000 and 2000. -Michael P.lo + rand() % (hi - lo) assuming you're using Phobos, where rand() returns a number in the range [0, uint.max]. This will get you a number in the range [1000, 2000); that is, it will be at least 1000 and at most 1999. If you need 2000 to be one of the numbers generated, use 2001 as the hi.
Oct 05 2008
Jarrett Billingsley wrote:On Sun, Oct 5, 2008 at 7:34 PM, Michael P. <baseball.mjp gmail.com> wrote:The random numbers will not be evenly distributed, though. You'll get more which are closer to 1000 than to 2000. (Imagine uint.max = 1000. Then 0 and 1000 map to 1000, but every other number has only one number which maps to it). Simple way to fix this is to ignore numbers from the non-uniform part: uint rmax = uint.max - (uint.max % (hi-lo)); uint r; do { r = rand(); } while (r>rmax); return lo + r % (hi - lo);Hi, How would I go about getting a random number that was in a specified range of 2 numbers? For example, getting a number inbetween 1000 and 2000. -Michael P.lo + rand() % (hi - lo) assuming you're using Phobos, where rand() returns a number in the range [0, uint.max]. This will get you a number in the range [1000, 2000); that is, it will be at least 1000 and at most 1999. If you need 2000 to be one of the numbers generated, use 2001 as the hi.
Oct 09 2008