Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
ddf71719
Commit
ddf71719
authored
Jun 27, 2018
by
Raymond Hettinger
Committed by
GitHub
Jun 27, 2018
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
bpo-24567: Random subnormal.diff (#7954)
Handle subnormal weights for choices()
parent
3c8043d8
Changes
3
Hide whitespace changes
Inline
Side-by-side
Showing
3 changed files
with
13 additions
and
1 deletion
+13
-1
Lib/random.py
Lib/random.py
+3
-1
Lib/test/test_random.py
Lib/test/test_random.py
+8
-0
Misc/NEWS.d/next/Library/2018-06-27-00-31-30.bpo-24567.FuePyY.rst
...S.d/next/Library/2018-06-27-00-31-30.bpo-24567.FuePyY.rst
+2
-0
No files found.
Lib/random.py
View file @
ddf71719
...
...
@@ -383,7 +383,9 @@ class Random(_random.Random):
raise
ValueError
(
'The number of weights does not match the population'
)
bisect
=
_bisect
.
bisect
total
=
cum_weights
[
-
1
]
return
[
population
[
bisect
(
cum_weights
,
random
()
*
total
)]
for
i
in
range
(
k
)]
hi
=
len
(
cum_weights
)
-
1
return
[
population
[
bisect
(
cum_weights
,
random
()
*
total
,
0
,
hi
)]
for
i
in
range
(
k
)]
## -------------------- real-valued distributions -------------------
...
...
Lib/test/test_random.py
View file @
ddf71719
...
...
@@ -227,6 +227,14 @@ class TestBasicOps:
with
self
.
assertRaises
(
IndexError
):
choices
([],
cum_weights
=
[],
k
=
5
)
def
test_choices_subnormal
(
self
):
# Subnormal weights would occassionally trigger an IndexError
# in choices() when the value returned by random() was large
# enough to make `random() * total` round up to the total.
# See https://bugs.python.org/msg275594 for more detail.
choices
=
self
.
gen
.
choices
choices
(
population
=
[
1
,
2
],
weights
=
[
1e-323
,
1e-323
],
k
=
5000
)
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
...
...
Misc/NEWS.d/next/Library/2018-06-27-00-31-30.bpo-24567.FuePyY.rst
0 → 100644
View file @
ddf71719
Improve random.choices() to handle subnormal input weights that could
occasionally trigger an IndexError.
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment