Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Array#sample randomness #2530

Merged
merged 1 commit into from
Mar 16, 2023
Merged

Fix Array#sample randomness #2530

merged 1 commit into from
Mar 16, 2023

Conversation

takaram
Copy link
Member

@takaram takaram commented Mar 15, 2023

Result of Array#sample is biased as shown below.
This PR fixes it.

Test script

n = 2
array = [0, 1, 2]
h = array.permutation(n).map { [_1, 0] }.to_h

p 100000.times.map { array.sample(n) }.tally(h)

Result

n = 2

{[0, 1]=>22253, [0, 2]=>11210, [1, 0]=>22379, [1, 2]=>11014, [2, 0]=>10970, [2, 1]=>22174}

n = 3

{[0, 1, 2]=>14988, [0, 2, 1]=>18262, [1, 0, 2]=>18453, [1, 2, 0]=>18645, [2, 0, 1]=>14864, [2, 1, 0]=>14788}

Note that the implemetation employs Fisher–Yates shuffle algorithm.

Copy link
Member

@elia elia left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@elia elia merged commit fd8dddd into opal:master Mar 16, 2023
@takaram takaram deleted the improve_array_sample branch March 16, 2023 09:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants