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!

Random number between 2 values 2

Status
Not open for further replies.

flaviooooo

Programmer
Feb 24, 2003
496
FR
Hey,

I'm looking for a way to create a random number between 2 values, for example between 20 and 40.

At the moment I use this code:
Code:
Public Function randomvalue(number As Integer)
Dim x As Integer

Randomize    ' Initialize random-number generator.

randomvalue = Int((number * Rnd) + 1)    ' Generate random value between 1 and number.

End Function

But as you can see, the lower limit will always be 1...

I tried this, to no avail:

Code:
Public Function randomvalue2(top As Integer, low As Integer)
Dim x As Integer

Randomize    ' Initialize random-number generator.

randomvalue2 = Int((top * Rnd) + low)    ' Generate random value between low and top.

End Function

Any help would be appreciated
 
Try this:
Code:
Public Function randomvalue2(top As Integer, low As Integer)
Dim x As Integer

Randomize    ' Initialize random-number generator.

randomvalue2 = Int((top-bottom+1) * Rnd + low)    ' Generate random value between low and top.

End Function

hth

Ben

----------------------------------------------
Ben O'Hara
David W. Fenton said:
We could be confused in exactly the same way, but confusion might be like Nulls, and not comparable.
 
Hey Ben, thanks... that works great for integers.

But I wanted to go 1 step further, and do the same for double-numbers and it doesn't seem to work anymore:

I did this code:

Code:
Public Function randomvalue_dbl(top As Double, low As Double)
Dim x As Integer

Randomize    ' Initialize random-number generator.

randomvalue_dbl = CDbl((top - low + 1) * Rnd + low) ' Generate random value between low and top.

End Function

and this example:

randomvalue_dbl(49,6400015258789, 49,6309015258789)
gave me 50,4484549583018

Any idea?
 
What about this ?
randomvalue_dbl = (top - low) * Rnd + low

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top