[flang-commits] [flang] [flang][runtime] Fix NEAREST() when exponent decreases (PR #75368)

via flang-commits flang-commits at lists.llvm.org
Wed Dec 13 11:21:30 PST 2023


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-flang-runtime

Author: Peter Klausler (klausler)

<details>
<summary>Changes</summary>

When the result of NEAREST() has an exponent less than that of the argument (e.g., NEAREST(1.,-1.) and NEAREST(-1.,1.)), the result was wrong, because the increment value uses the result of SPACING() in terms of the argument.  Fix by just calling into the C runtime routine std::nextafter().

---
Full diff: https://github.com/llvm/llvm-project/pull/75368.diff


2 Files Affected:

- (modified) flang/runtime/numeric.cpp (+3-5) 
- (modified) flang/unittests/Runtime/Numeric.cpp (+1-1) 


``````````diff
diff --git a/flang/runtime/numeric.cpp b/flang/runtime/numeric.cpp
index cd54e6b54a2e53..bb711d3b76eaad 100644
--- a/flang/runtime/numeric.cpp
+++ b/flang/runtime/numeric.cpp
@@ -247,12 +247,10 @@ template <int PREC, typename T> inline T Spacing(T x) {
 
 // NEAREST (16.9.139)
 template <int PREC, typename T> inline T Nearest(T x, bool positive) {
-  auto spacing{Spacing<PREC>(x)};
-  if (x == 0) {
-    auto least{std::numeric_limits<T>::denorm_min()};
-    return positive ? least : -least;
+  if (positive) {
+    return std::nextafter(x, std::numeric_limits<T>::infinity());
   } else {
-    return positive ? x + spacing : x - spacing;
+    return std::nextafter(x, -std::numeric_limits<T>::infinity());
   }
 }
 
diff --git a/flang/unittests/Runtime/Numeric.cpp b/flang/unittests/Runtime/Numeric.cpp
index 5afed750c0b183..43263d1ac42315 100644
--- a/flang/unittests/Runtime/Numeric.cpp
+++ b/flang/unittests/Runtime/Numeric.cpp
@@ -86,7 +86,7 @@ TEST(Numeric, Nearest) {
   EXPECT_EQ(RTNAME(Nearest8)(Real<8>{1.0}, true),
       Real<8>{1.0} + std::ldexp(Real<8>{1.0}, -52));
   EXPECT_EQ(RTNAME(Nearest8)(Real<8>{1.0}, false),
-      Real<8>{1.0} - std::ldexp(Real<8>{1.0}, -52));
+      Real<8>{1.0} - 0.5 * std::ldexp(Real<8>{1.0}, -52));
 }
 
 TEST(Numeric, Nint) {

``````````

</details>


https://github.com/llvm/llvm-project/pull/75368


More information about the flang-commits mailing list