Site Tools


Generate Random Numbers

Developer: RhinoScript
Summary: How to generate random numbers that fall within a specified range.

Sample Code

The following code sample demonstrates how to generate random integers that fall within a specified range.

First, the standard VBScript method:

 Sub Test1()
   nLow = 1
   nHigh = 100
   Randomize
   Rhino.Print Int((nHigh - nLow + 1) * Rnd + nLow)
 End Sub

Note, since the Int function always rounds down, we add one to the difference between the limits.

Now, a little help from the .NET Framework:

 Sub Test2()
   nLow = 1
   nHigh = 100
   Set objRandom = CreateObject("System.Random")
   Rhino.Print objRandom.Next_2(nLow, nHigh)
 End Sub

If you want a random floating point number that falls within a specified range, you can use the technique below.

 Sub Test3()
   dblLow = 10.0
   dblHigh = 50.0
   Randomize
   Rhino.Print Rnd * (dblHigh - dblLow) + dblLow
 End Sub
developer/scriptsamples/randomnumber.txt ยท Last modified: 2011/11/11 by dale