The *weights* or *cum_weights* can use any numeric type that interoperates
with the :class:`float` values returned by :func:`random` (that includes
- integers, floats, and fractions but excludes decimals). Weights are
- assumed to be non-negative.
+ integers, floats, and fractions but excludes decimals). Behavior is
+ undefined if any weight is negative. A :exc:`ValueError` is raised if all
+ weights are zero.
For a given seed, the :func:`choices` function with equal weighting
typically produces a different sequence than repeated calls to
.. versionadded:: 3.6
+ .. versionchanged:: 3.9
+ Raises a :exc:`ValueError` if all weights are zero.
+
.. function:: shuffle(x[, random])
raise TypeError('Cannot specify both weights and cumulative weights')
if len(cum_weights) != n:
raise ValueError('The number of weights does not match the population')
- bisect = _bisect
total = cum_weights[-1] + 0.0 # convert to float
+ if total <= 0.0:
+ raise ValueError('Total of weights must be greater than zero')
+ bisect = _bisect
hi = n - 1
return [population[bisect(cum_weights, random() * total, 0, hi)]
for i in _repeat(None, k)]
choices = self.gen.choices
choices(population=[1, 2], weights=[1e-323, 1e-323], k=5000)
+ def test_choices_with_all_zero_weights(self):
+ # See issue #38881
+ with self.assertRaises(ValueError):
+ self.gen.choices('AB', [0.0, 0.0])
+
def test_gauss(self):
# Ensure that the seed() method initializes all the hidden state. In
# particular, through 2.2.1 it failed to reset a piece of state used
--- /dev/null
+random.choices() now raises a ValueError when all the weights are zero.