Normal Topic @Random() question (Read 639 times)
JimChet
Member
*
Offline


No personal text

Posts: 9
Location: Northern California
Joined: Mar 13th, 2006
@Random() question
May 12th, 2011 at 4:28pm
Print Post Print Post  
Is it possible to generate an random integer number within a certain range?   eg. between 122 and 333?
  
Back to top
 
IP Logged
 
The Cow
YaBB Administrator
*****
Offline



Posts: 2530
Joined: Nov 22nd, 2002
Re: @Random() question
Reply #1 - May 12th, 2011 at 4:52pm
Print Post Print Post  
Because "random(n as double) as double" sets a ceiling (the argument "n") but not a floor, you should multiply the result of random(1.0) by the range you want to generate and then add the floor value:

Code
Select All
var aa as double
var result as int

aa = Random(1.0)
result = ((333 - 122) * aa) + 122
writeln(result)
 



Of course, you should simplify "333 - 122" to 211, but I left it in to be illustrative of the range.
  

Mark Lasersohn&&Programmer&&Lantica Software, LLC
Back to top
IP Logged
 
Carl Underwood
Senior Member
Members
*****
Offline



Posts: 1351
Location: New Hampshire
Joined: Mar 11th, 2003
Re: @Random() question
Reply #2 - May 25th, 2011 at 4:03am
Print Post Print Post  
There's one small problem with this code.  Wink

Since the result is being converted to an integer, the fractions are always thrown away. The outcome is that the maximum number in the range will never be returned. I discovered this a couple years ago while writing a similar piece of code.

The fix is to add 0.5 before it's converted to an integer. This way, it will be able to produce results for the entire range.
Code
Select All
var aa as double
var result as int

aa = Random(1.0)
result = ((333 - 122) * aa) + 122.5
writeln(result)
 




You can verify that entire range is possible, by running the following code in a mass update on a single record.
Code
Select All
var result as int
var i as int

For i = 1 to 5000
	result = Random(333 - 122) + 122.5

	If result < 123 or result > 332
	writeln(result)
Next 



If you change "122.5" to "122", you will see that the slate will never display 333, only 122.
  


Carl Underwood
CDU Computer Consulting LLC
Epsom, New Hampshire
Back to top
IP Logged