14

Quick Tip - Get-Random Is Weird - Doesn't Include The Maximum Value

 3 years ago
source link: https://thomasrayner.ca/quick-tip-get-random-is-weird-doesnt-include-the-maximum-value/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Quick Tip - Get-Random Is Weird - Doesn't Include The Maximum Value

The PowerShell command Get-Random is kind of weird. Consider the following script:

while ($true)
{
    Get-Random -Minimum 1 -Maximum 2
    sleep 1
}

Run it on your own computer. Every second, it should write a random number between 1 and 2 until you interrupt it (CTRL + C). You would expect a somewhat balanced output of 1’s and 2’s like if you were recording the outcomes of repeatedly flipping a coin. Right? Wrong. You will get a string of 1’s and never ever EVER get a 2. Change the Maximum to 3 and you will get 1’s and 2’s but no 3’s.

Apparently the maximum value of the Get-Random command isn’t a valid value to return, but, the minimum is. It’s possible that there is a condition where the command will work as expected but I haven’t experimented enough to know for sure.

Weird.

Written on February 18, 2015

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK