Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Randomizing

Status
Not open for further replies.

Sheriff

Programmer
Sep 1, 2001
34
US
How do you get a random number between numbers like 40 and 50.

A = int(15 * rnd + 1)

This gives 1 - 15.

A = int(50 * rnd + 40)

This gives numbers up to 80...what am I doing wrong...?
 
[tt]INT((upperbound - lowerbound + 1) * RND + lowerbound)
A = INT((50 - 40 + 1) * RND + 40)
A = INT(11 * RND + 40)
[/tt]

VCA.gif

Alt255@Vorpalcom.Intranets.com​
 
Think of it as a series of conversions of ranges. The RND function provides you with the range [0,1), and you want the range [40,51) (note the exclusion at the upper end). The first step should be to set the magnitude of the ranges. [40,51) is the same magnitude (size) as [0,11), so you need to multiply the value returned by RND by 11 (note that this value is the lower bound subtracted from the upper bound). After this point, you have the range [0,11), and you want to translate this up to [40,51). This is easy; just add 40.

The rule of converting ranges is that whatever you do your number you also do to both ends of the range.

That said, the following function will concisely return an integer inside the specified range, inclusively at both ends:
[tt]
FUNCTION getRandomInteger%(leastNumber%, greatestNumber%)
rangeSize% = greatestNumber% - leastNumber% + 1
getRandomInteger% = (rangeSize% * RND) + leastNumber%
END FUNCTION[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top