1 //===-- Unittests for sqrtf -----------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===---------------------------------------------------------------------===// 8 9 #include "include/math.h" 10 #include "src/math/sqrtf.h" 11 #include "utils/FPUtil/FPBits.h" 12 #include "utils/FPUtil/TestHelpers.h" 13 #include "utils/MPFRWrapper/MPFRUtils.h" 14 15 using FPBits = __llvm_libc::fputil::FPBits<float>; 16 using UIntType = typename FPBits::UIntType; 17 18 namespace mpfr = __llvm_libc::testing::mpfr; 19 20 constexpr UIntType HiddenBit = 21 UIntType(1) << __llvm_libc::fputil::MantissaWidth<float>::value; 22 23 float nan = FPBits::buildNaN(1); 24 float inf = FPBits::inf(); 25 float negInf = FPBits::negInf(); 26 27 TEST(SqrtfTest, SpecialValues) { 28 ASSERT_FP_EQ(nan, __llvm_libc::sqrtf(nan)); 29 ASSERT_FP_EQ(inf, __llvm_libc::sqrtf(inf)); 30 ASSERT_FP_EQ(nan, __llvm_libc::sqrtf(negInf)); 31 ASSERT_FP_EQ(0.0f, __llvm_libc::sqrtf(0.0f)); 32 ASSERT_FP_EQ(-0.0f, __llvm_libc::sqrtf(-0.0f)); 33 ASSERT_FP_EQ(nan, __llvm_libc::sqrtf(-1.0f)); 34 ASSERT_FP_EQ(1.0f, __llvm_libc::sqrtf(1.0f)); 35 ASSERT_FP_EQ(2.0f, __llvm_libc::sqrtf(4.0f)); 36 ASSERT_FP_EQ(3.0f, __llvm_libc::sqrtf(9.0f)); 37 } 38 39 TEST(SqrtfTest, DenormalValues) { 40 for (UIntType mant = 1; mant < HiddenBit; mant <<= 1) { 41 FPBits denormal(0.0f); 42 denormal.mantissa = mant; 43 44 ASSERT_MPFR_MATCH(mpfr::Operation::Sqrt, float(denormal), 45 __llvm_libc::sqrtf(denormal), 0.5); 46 } 47 48 constexpr UIntType count = 1'000'001; 49 constexpr UIntType step = HiddenBit / count; 50 for (UIntType i = 0, v = 0; i <= count; ++i, v += step) { 51 float x = *reinterpret_cast<float *>(&v); 52 ASSERT_MPFR_MATCH(mpfr::Operation::Sqrt, x, __llvm_libc::sqrtf(x), 0.5); 53 } 54 } 55 56 TEST(SqrtfTest, InFloatRange) { 57 constexpr UIntType count = 10'000'001; 58 constexpr UIntType step = UIntType(-1) / count; 59 for (UIntType i = 0, v = 0; i <= count; ++i, v += step) { 60 float x = *reinterpret_cast<float *>(&v); 61 if (isnan(x) || (x < 0)) { 62 continue; 63 } 64 65 ASSERT_MPFR_MATCH(mpfr::Operation::Sqrt, x, __llvm_libc::sqrtf(x), 0.5); 66 } 67 } 68