-
Notifications
You must be signed in to change notification settings - Fork 4.9k
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
Random.NextBytes is very slightly biased against 0xFF #41457
Comments
I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label. |
Possible dupe of #23198. |
@GrabYourPitchforks - I mean, that issue is about the fact that there's a deviation in the algorithm used to generate what This one is more about how there's a slight bias due to the fact that Although yes, it may end up being a dupe due to the resolution. I just wanted this explicitly called out. |
Ah, yes, you're right in that it's not an exact dupe. But the resolution would be the same. Either they're all resolved as "by design", or they're fixed all at once. |
Note to future readers: The fix implemented at this time only affects randoms created without an explicit seed. Due to compatibility concerns, randoms initialized with a seed retain the old behavior. |
NextBytes(byte[])
is implemented like so:(side note: why no
unchecked
on the cast...?)The
Span<byte>
version has the same effective implementation ifNext()
has not been overridden.The problem is that
InternalSample()
returns values in the range [0
,int.MaxValue
) - that is,int.MaxValue
is not included. This skews the distribution of possible values for bytes:0x00
-0xFE
- 8388608 values0xFF
- 8388607 values(Sample generation program)
The catch is that I'm not sure that this is fixable, given that any fix for this would be a breaking change in the behavior, and we've been reluctant to do so for other parts of
Random
.The text was updated successfully, but these errors were encountered: