[flang-commits] [PATCH] D127020: [flang][runtime] Ensure that 0. <= RANDOM_NUMBER() < 1.

Peter Klausler via Phabricator via flang-commits flang-commits at lists.llvm.org
Fri Jun 3 15:51:57 PDT 2022


klausler created this revision.
klausler added a reviewer: vdonaldson.
klausler added a project: Flang.
Herald added a subscriber: jdoerfert.
Herald added a project: All.
klausler requested review of this revision.

It was possible for RANDOM_NUMBER() to return 1.0.


https://reviews.llvm.org/D127020

Files:
  flang/runtime/random.cpp


Index: flang/runtime/random.cpp
===================================================================
--- flang/runtime/random.cpp
+++ flang/runtime/random.cpp
@@ -54,17 +54,23 @@
   {
     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);
     }
   }


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D127020.434178.patch
Type: text/x-patch
Size: 1450 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/flang-commits/attachments/20220603/0ee7a121/attachment.bin>


More information about the flang-commits mailing list