diff options
author | 2018-04-18 11:46:07 -0700 | |
---|---|---|
committer | 2018-04-18 11:48:46 -0700 | |
commit | 31f925c7783fb8fa58278b31585dcf7bdb4cfd8c (patch) | |
tree | 36447c2455927321989e6cdbc65b8268187b2c3b /tensorflow/core/lib/random | |
parent | ce7a92a62a6bbf0765e68a3340fe3efb07ac1e2b (diff) |
Change operands of subtraction expression to have well-defined behaviour.
At present, signed arithmetic overflows (i.e. has undefined behaviour) in general, e.g. when computing 0 - INT_MIN or INT_MAX - INT_MIN. The fact that we want the result in the unsigned type does not help us here.
The fix is to convert the operands to the corresponding unsigned type first and then perform the operation in unsigned arithmetic, which is well-defined and has the correct subtraction behaviour.
PiperOrigin-RevId: 193391813
Diffstat (limited to 'tensorflow/core/lib/random')
-rw-r--r-- | tensorflow/core/lib/random/random_distributions.h | 6 |
1 files changed, 4 insertions, 2 deletions
diff --git a/tensorflow/core/lib/random/random_distributions.h b/tensorflow/core/lib/random/random_distributions.h index ad16dbf01f..4cf3a999f6 100644 --- a/tensorflow/core/lib/random/random_distributions.h +++ b/tensorflow/core/lib/random/random_distributions.h @@ -164,7 +164,8 @@ class UniformDistribution<Generator, int32> { typedef int32 ResultElementType; // Must have lo < hi - UniformDistribution(int32 lo, int32 hi) : lo_(lo), range_(hi - lo) {} + UniformDistribution(int32 lo, int32 hi) + : lo_(lo), range_(static_cast<uint32>(hi) - static_cast<uint32>(lo)) {} PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { @@ -198,7 +199,8 @@ class UniformDistribution<Generator, int64> { typedef int64 ResultElementType; // Must have lo < hi - UniformDistribution(int64 lo, int64 hi) : lo_(lo), range_(hi - lo) {} + UniformDistribution(int64 lo, int64 hi) + : lo_(lo), range_(static_cast<uint64>(hi) - static_cast<uint64>(lo)) {} PHILOX_DEVICE_INLINE ResultType operator()(Generator* gen) { |