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.

1

u/Inothernews1 Jul 03 '26 edited Jul 22 '26

I was curious whether the data actually supported a bias, so I pooled all 10 runs and tested the null hypothesis that the first element is selected with probability 0.5.

Across all 10,000,000 trials:

  • First element selected: 5,001,554

  • Second element selected: 4,998,446

Using an exact two-sided binomial test:

from scipy.stats import binomtest

result = binomtest(5_001_554, n=10_000_000, p=0.5)
print(result.pvalue)

and the result:

p = 0.326

That's way above 0.05, meaning it's nowhere near statistically significant.

For completeness, I also tested each individual 1,000,000-sample run. Their p-values were approximately:

0.970, 0.593, 0.224, 0.699, 0.615, 0.788, 0.510, 0.191, 0.422, 0.257

None are statistically significant either.

Based on these results, I don't think this dataset provides evidence that Get-Random prefers the first element. The small differences are exactly the kind of fluctuations you'd expect from random sampling.