developer:scriptsamples:randomnumber


Generate Random Numbers

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: 2010/01/26 16:37 (external edit) Driven by DokuWiki Recent changes RSS feed

 © 1997-2010 

McNeel North America Europe Latin AmericaAsia