× The internal search function is temporarily non-functional. The current search engine is no longer viable and we are researching alternatives.
As a stop gap measure, we are using Google's custom search engine service.
If you know of an easy to use, open source, search engine ... please contact support@midrange.com.


  • Subject: Re: Controlling ('rand') random number upper limit
  • From: Chris Rehm <javadisciple@xxxxxxxxxxxxx>
  • Date: Mon, 18 Jun 2001 20:32:36 -0700
  • User-Agent: Mozilla/5.0 (Windows; U; Win98; en-US; m18) Gecko/20010131 Netscape6/6.01

Paul Jackson wrote:

Paul, the solution you found is the most accurate one. You can, as been 
pointed out, simply divide the random number generated by the range of 
the number you want and take the remainder. But that is not exactly 
accurate. Let's suppose you wish to generate a number between 1 and 
100.  327 times out of 328 it will return a number between 0 and 99, add 
one and you have the random number you wanted to generate. But once out 
of 328 tries it will generate a number between 32700 and 32768, not 
32799. So there is no chance you will generate a number between 69-100 
using this method. So your random generation is slightly skewed.

The method you have found, using the ratio of the number to it's range 
and applying that to the range of number that you want will give as a 
distribution that is as random as the numbers provided by the generator.

All that said, it might be that the generator isn't all that flat 
either, and you might not care if you are all that perfect in your 
distribution (I don't know your application). So you just need to decide 
between accuracy and ease of coding.

> Thanks to all who replied.
> 
> I finally got the algorithm for returning a random
> number within a specified range (lo,hi).
> 
> FinalRandomNbr = ((NbrFromRandFunc / 32768) *
> ((HiRange - LoRange) + 1)) + LoRange
> 
> NbrFromRandFunc is an integer in the range 0 thru
> 32767 inclusive.
> It is divided by 32768 to return a number between 0
> and 1.
> The result is multipied by the total number of
> different values possible and LoRange is added to bump
> it into the correct range.
> 
> If there is an easier way of doing it please let me
> know.
> 
> -Paul



    Chris Rehm
<mailto:javadisciple@earthlink.net>



As an Amazon Associate we earn from qualifying purchases.

This thread ...

Follow-Ups:
Replies:

Follow On AppleNews
Return to Archive home page | Return to MIDRANGE.COM home page

This mailing list archive is Copyright 1997-2024 by midrange.com and David Gibbs as a compilation work. Use of the archive is restricted to research of a business or technical nature. Any other uses are prohibited. Full details are available on our policy page. If you have questions about this, please contact [javascript protected email address].

Operating expenses for this site are earned using the Amazon Associate program and Google Adsense.