Saturday, January 20, 2007

Random Numbers in PowerShell

With PowerShell, you can leverage the .NET Framework's System.Random class to create random numbers. To create a random numbers you must first create a new random number object, then the object's methods to generate a random number as follows:
$rand = New-Object  System.Random
$rand.next()

If you want  a random  number  between 0 and  1, you can use the .NextDouble method which woule look like this:
PSH [D:\foo]: $rand = New-Object system.random
PSH [D:\foo]: $rand.nextdouble()
0.370553521611986
PSH [D:\foo]:
$rand.nextdouble()0.561135980561905
If you want to create random numbers that  are between two other numbers (e.g. a random number  between 1 and 10, or between  4 and 16), you can specify a bottom and top range in a call to .NEXT(), where the first number is part of the range, but the second is above the max value you wish to compute, as shown   here:
PSH [D:\foo]: $rand = New-Object system.randomPSH [D:\foo]: $rand.next(1,11) # gets random number between 1 and 10
7
PSH [D:\foo]: $rand.next(4,17)
# gets random number between 5 and 16
14


Thanks to a couple of readers who spotted that the second parameter was exclusive.

5 comments:

Ry Jones said...

This isn't quite correct. To generate a number between 4 and 16, you need to use (4,17)

Unknown said...

check this out
$r.Next(0,1) never generate one it is always 0 so the upper bound is not inclusive.

Unknown said...

You are both correct. The upper bound is actually exclusive. So to create a number between 1 and ten, you'd use next(1,11). Some may regard this as a bug of the API. For others it's a feature.

Thomas Lee said...

Well spotted. The second parameter is exclusive. To create a random number between 0 and 1, you'd type $r.next(0,2).

Thanks for spotting this.

leftler said...

@tim, It is most definitely not a feature.

If you have an array it is indexed 0 to length-1. Using Next you can just call "Next(0, myArray.Length)" and always get a valid index.