[flang-commits] [flang] f3278e0 - [flang][runtime] Ensure that 0. <= RANDOM_NUMBER() < 1.
Peter Klausler via flang-commits
flang-commits at lists.llvm.org
Fri Jun 3 22:44:30 PDT 2022
Author: Peter Klausler
Date: 2022-06-03T22:44:19-07:00
New Revision: f3278e0f3cfeb7cd1519b0b9154ccdc28f3410b5
URL: https://github.com/llvm/llvm-project/commit/f3278e0f3cfeb7cd1519b0b9154ccdc28f3410b5
DIFF: https://github.com/llvm/llvm-project/commit/f3278e0f3cfeb7cd1519b0b9154ccdc28f3410b5.diff
LOG: [flang][runtime] Ensure that 0. <= RANDOM_NUMBER() < 1.
It was possible for RANDOM_NUMBER() to return 1.0.
Differential Revision: https://reviews.llvm.org/D127020
Added:
Modified:
flang/runtime/random.cpp
Removed:
################################################################################
diff --git a/flang/runtime/random.cpp b/flang/runtime/random.cpp
index 8f8145b299f4a..93461e436c6ae 100644
--- a/flang/runtime/random.cpp
+++ b/flang/runtime/random.cpp
@@ -54,17 +54,23 @@ inline void Generate(const Descriptor &harvest) {
{
CriticalSection critical{lock};
for (std::size_t j{0}; j < elements; ++j) {
- Int fraction{generator()};
- if constexpr (words > 1) {
- for (std::size_t k{1}; k < words; ++k) {
- static constexpr auto rangeMask{(GeneratedWord{1} << rangeBits) - 1};
- GeneratedWord word{(generator() - generator.min()) & rangeMask};
- fraction = (fraction << rangeBits) | word;
+ while (true) {
+ Int fraction{generator()};
+ if constexpr (words > 1) {
+ for (std::size_t k{1}; k < words; ++k) {
+ static constexpr auto rangeMask{
+ (GeneratedWord{1} << rangeBits) - 1};
+ GeneratedWord word{(generator() - generator.min()) & rangeMask};
+ fraction = (fraction << rangeBits) | word;
+ }
+ }
+ fraction >>= words * rangeBits - PREC;
+ REAL next{std::ldexp(static_cast<REAL>(fraction), -(PREC + 1))};
+ if (next >= 0.0 && next < 1.0) {
+ *harvest.Element<REAL>(at) = next;
+ break;
}
}
- fraction >>= words * rangeBits - PREC;
- *harvest.Element<REAL>(at) =
- std::ldexp(static_cast<REAL>(fraction), -(PREC + 1));
harvest.IncrementSubscripts(at);
}
}
More information about the flang-commits
mailing list