[libc-commits] [libc] [llvm] [libc][math] Implement C23 half precision erf function (PR #179251)

via libc-commits libc-commits at lists.llvm.org
Tue Mar 10 10:03:23 PDT 2026


================
@@ -0,0 +1,90 @@
+//===-- Implementation header for erff16 ------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC___SUPPORT_MATH_ERFF16_H
+#define LLVM_LIBC_SRC___SUPPORT_MATH_ERFF16_H
+
+#include "include/llvm-libc-macros/float16-macros.h"
+
+#ifdef LIBC_TYPES_HAS_FLOAT16
+
+#include "common_constants.h" // ERFF_COEFFS
+#include "src/__support/FPUtil/FEnvImpl.h"
+#include "src/__support/FPUtil/FPBits.h"
+#include "src/__support/FPUtil/multiply_add.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
+
+namespace LIBC_NAMESPACE_DECL {
+
+namespace math {
+
+LIBC_INLINE float16 erff16(float16 x) {
+  using namespace common_constants_internal;
+
+  using FPBits = typename fputil::FPBits<float16>;
+  FPBits xbits(x);
+  uint16_t x_abs = xbits.abs().uintval();
+
+  // |x| >= 4.0
+  if (LIBC_UNLIKELY(x_abs >= 0x4400U)) {
+    // Check for NaN or Inf
+    if (LIBC_UNLIKELY(x_abs >= 0x7c00U)) {
+      if (x_abs > 0x7c00U) {
+        if (xbits.is_signaling_nan()) {
+          fputil::raise_except_if_required(FE_INVALID);
+          return FPBits::quiet_nan().get_val();
+        }
+        return x;
+      }
+      // Inf -> returns 1.0 or -1.0
+      return xbits.is_neg() ? -1.0f16 : 1.0f16;
+    }
+
+    return static_cast<float16>(xbits.is_neg() ? -1.0 - x * 0x1.0p-50
----------------
lntue wrote:

Do you want to do these computations in double precision? or float is enough?  Make sure that the computations are all of the same type.  Also use `fputil::cast` instead of `static_cast`.

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


More information about the libc-commits mailing list