cpython icon indicating copy to clipboard operation
cpython copied to clipboard

random.choices undefined behavior when some weights are not finite or negative

Open leikdga opened this issue 1 year ago • 0 comments

Feature or enhancement

Problem

In current doc of random module, it is mentioned that

Weights are assumed to be non-negative and finite.

But what will happen if user violates this rule?

The program will just give strange result, which is also counter intuitive.

Here are some examples,

from collections import Counter
import random

l = random.choices([1, 2, 3], weights=[2, -1, 1], k=1000)
print(Counter(l))  # Counter({3: 513, 1: 487})

l = random.choices([1, 2, 3], cum_weights=[2, float("inf"), 3], k=1000)
print(Counter(l))  # Counter({1: 658, 2: 342})

Proposal

We could explicitly raise an exception in such cases.

Has this already been discussed elsewhere?

As far as I'm aware, no.

Links to previous discussion of this feature:

N/A

Linked PRs

  • gh-118962

leikdga avatar May 12 '24 04:05 leikdga