diff options
author | Tim Peters <tim.peters@gmail.com> | 2003-06-19 03:46:46 (GMT) |
---|---|---|
committer | Tim Peters <tim.peters@gmail.com> | 2003-06-19 03:46:46 (GMT) |
commit | 76ca1d428f96284ed58f4523b698ed95c6fdbdb2 (patch) | |
tree | b2de2b8f49ffdab9413ab970e348a4dfb4daa7a7 | |
parent | afb8979771e78ef8fe3d610c023463f7ec4f3e1b (diff) | |
download | cpython-76ca1d428f96284ed58f4523b698ed95c6fdbdb2.zip cpython-76ca1d428f96284ed58f4523b698ed95c6fdbdb2.tar.gz cpython-76ca1d428f96284ed58f4523b698ed95c6fdbdb2.tar.bz2 |
randrange(): Repaired my overly optimistic rewrite, and added comments
explaining what's wrong with the two simpler variants.
-rw-r--r-- | Lib/random.py | 14 |
1 files changed, 13 insertions, 1 deletions
diff --git a/Lib/random.py b/Lib/random.py index 0937ba2..1ae2553 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -148,7 +148,19 @@ class Random(_random.Random): if istop != stop: raise ValueError, "non-integer stop for randrange()" if step == 1 and istart < istop: - return int(istart + self.random()*(istop - istart)) + # Note that + # int(istart + self.random()*(istop - istart)) + # instead would be incorrect. For example, consider istart + # = -2 and istop = 0. Then the guts would be in + # -2.0 to 0.0 exclusive on both ends (ignoring that random() + # might return 0.0), and because int() truncates toward 0, the + # final result would be -1 or 0 (instead of -2 or -1). + # istart + int(self.random()*(istop - istart)) + # would also be incorrect, for a subtler reason: the RHS + # can return a long, and then randrange() would also return + # a long, but we're supposed to return an int (for backward + # compatibility). + return int(istart + int(self.random()*(istop - istart))) if step == 1: raise ValueError, "empty range for randrange()" |