Skip to content

Fix Random.NextSingle being able to return 1.0 - #666

Merged
SimonCropp merged 2 commits into
mainfrom
fix/random-nextsingle-range
Oct 11, 2026
Merged

SimonCropp merged 2 commits into
mainfrom
fix/random-nextsingle-range

Conversation

@SimonCropp

Copy link
Copy Markdown
Owner

Bug

The Random.NextSingle polyfill (below net6) was (float) target.NextDouble(). A double just below 1.0 rounds up to exactly 1.0f when cast, which is outside the documented [0, 1) range. It is rare but real: new Random(0) returns 1.0f on call 5,800,140 on net48.

Fix

Sample again while the cast result is not below 1f. This is what the BCL does for its seeded implementation.

Test

RandomNextSingle_NeverReturnsOne takes 5,900,000 values from new Random(0) and asserts the maximum is below 1.0f and the minimum is not below 0.0f. It failed on net48 before the fix (maximum was 1), and passes on net462 and net48 (polyfill) and net10.0 (BCL).

@SimonCropp SimonCropp added this to the 11.4.4 milestone Oct 11, 2026
@SimonCropp
SimonCropp merged commit d3f0547 into main Oct 11, 2026
4 checks passed
@SimonCropp
SimonCropp deleted the fix/random-nextsingle-range branch October 11, 2026 22:10
This was referenced Oct 12, 2026
This was referenced Oct 13, 2026
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.

1 participant