From: Kevin Boyd Date: Mon, 6 Jul 2020 01:37:21 +0000 (-0700) Subject: Avoid overflow in RNG X-Git-Url: http://biod.pnpi.spb.ru/gitweb/?a=commitdiff_plain;h=b3a7daa179b7935c3178cfccbe1c9ca4117a405e;p=alexxy%2Fgromacs.git Avoid overflow in RNG Instead of checking for overflow, get necessary information about number of bits from type attributes. This technically wasn't undefined behavior but with strict UBSAN settings got tagged in tests. --- diff --git a/src/gromacs/random/uniformrealdistribution.h b/src/gromacs/random/uniformrealdistribution.h index bc7cb61405..bdaf090018 100644 --- a/src/gromacs/random/uniformrealdistribution.h +++ b/src/gromacs/random/uniformrealdistribution.h @@ -107,8 +107,7 @@ RealType generateCanonical(Rng& g) // No point in using more bits than fit in RealType const uint64_t digits = std::numeric_limits::digits; const uint64_t realBits = std::min(digits, static_cast(Bits)); - const uint64_t range = Rng::max() - Rng::min() + uint64_t(1); - uint64_t log2R = (range == 0) ? std::numeric_limits::digits : log2I(range); + const uint64_t log2R = std::numeric_limits::digits; uint64_t k = realBits / log2R + (realBits % log2R != 0) + (realBits == 0); // Note that Rng::max and Rng::min are typically an integer type. // Only unsigned integer types can express the range using the