Urgent.News

What's breaking now, across thousands of outlets.

Tech

When random is not actually random enough

Picking a random object from a set is a common task programmers face. The usual approach is to generate a random number, then use modulo to select an object from the set. However, this method does not guarantee a uniform distribution of choices. For example, when selecting from a set of three objects, the first choice is 40% likely to be picked, while the other two have only a 30% chance each. This issue arises because the modulo operation does not preserve the original uniform distribution of the random number generator.

A proper solution for picking objects uniformly would be a function called random_between(l, h), which assigns each number between l and h an equal chance of being selected. The API design issue lies in the fact that random_u64() offers a low-level, specialized solution for generating uniform random numbers. While it may be useful in certain cases, it is not the ideal tool for selecting objects from a set, especially when you want to give different weights to different objects.

A better approach would be to create a random_choice() function that takes a set of discrete options and their corresponding probabilities. This way, you can explicitly define the probability distribution and ensure that the selection process respects the intended weights. For instance, you could represent the probability distribution as [(Blue, 10), (Red, 5)] instead of using floating-point numbers that sum to 1.0.

This change would make the code easier to reason about, reduce floating-point instability, and prevent errors in probability calculations.

Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at ersc.io →

More in Tech

More from Wednesday 7 October →