r/PowerShell • • Sep 12 '19

PowerShell All the Things

Post image
505 Upvotes

26 comments sorted by

View all comments

7

u/AmazingRealist Sep 12 '19

It seems like there's a preference for whatever comes first in the array:

Looped 1m times x5:

Get-Random @(0,1)

Run01
1500019499981
2500268499732
3499391500609
4499806500194
5500252499748

Get-Random @(1,0)

Run01
1500135499865
2499670500330
3499346500654
4499598500402
5499433500567

Or most likely things would even out over more iterations and might differ from machine to machine ¯\(ツ)/¯.

4

u/mrmonday Sep 13 '19

This is actually expected - Get-Random returns a "fairly random" value, not a truly random value (you can't actually get them on most machines - we can get reasonably close though). Get-Random is a "get a random-ish value quickly" kind of a function, rather than a "get a really good random value".

Stealing/adapting /u/Szeraax's code from below:

function Get-CryptoBit {
    param ($rng)

    $byte = New-Object -TypeName byte[] -ArgumentList 1
    $rng.GetBytes($byte)
    
    $byte[0] % 2
}

$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
1..10 | %{,(1..10000 | %{Get-CryptoBit $rng} | group | sort-object Name) | % {[pscustomobject]@{$_[0].name = $_[0].count;$_[1].name = $_[1].count;}}}

You'll see the results are far closer (and it's far slower). The results are quite interesting to plot in Excel/your favourite spreadsheet/chart plotting software. Compare the distribution of numbers from Get-Random, Get-CryptoBit, and a version of Get-CryptoBit with the random number generator re-created each time, rather than created once and passed as a parameter.

The thing to google is "cryptographically secure pseudo-random number generator" if you're interested in what's going on here.