Skip to content

Random.NextBytes is very slightly biased against 0xFF #41457

@Clockwork-Muse

Description

@Clockwork-Muse

NextBytes(byte[]) is implemented like so:

public virtual void NextBytes(byte[] buffer)
{
    if (buffer == null) throw new ArgumentNullException(nameof(buffer));
    for (int i = 0; i < buffer.Length; i++)
    {
        buffer[i] = (byte)InternalSample();
    }
}

(side note: why no unchecked on the cast...?)

The Span<byte> version has the same effective implementation if Next() 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 values
  • 0xFF - 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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions