1 //===-- Unittests for sqrt -----------------------------------------------===// 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/sqrt.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<double>; 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<double>::value; 22 23 double nan = FPBits::buildNaN(1); 24 double inf = FPBits::inf(); 25 double negInf = FPBits::negInf(); 26 27 TEST(SqrtTest, SpecialValues) { 28 ASSERT_FP_EQ(nan, __llvm_libc::sqrt(nan)); 29 ASSERT_FP_EQ(inf, __llvm_libc::sqrt(inf)); 30 ASSERT_FP_EQ(nan, __llvm_libc::sqrt(negInf)); 31 ASSERT_FP_EQ(0.0, __llvm_libc::sqrt(0.0)); 32 ASSERT_FP_EQ(-0.0, __llvm_libc::sqrt(-0.0)); 33 ASSERT_FP_EQ(nan, __llvm_libc::sqrt(-1.0)); 34 ASSERT_FP_EQ(1.0, __llvm_libc::sqrt(1.0)); 35 ASSERT_FP_EQ(2.0, __llvm_libc::sqrt(4.0)); 36 ASSERT_FP_EQ(3.0, __llvm_libc::sqrt(9.0)); 37 } 38 39 TEST(SqrtTest, DenormalValues) { 40 for (UIntType mant = 1; mant < HiddenBit; mant <<= 1) { 41 FPBits denormal(0.0); 42 denormal.mantissa = mant; 43 44 ASSERT_MPFR_MATCH(mpfr::Operation::Sqrt, double(denormal), 45 __llvm_libc::sqrt(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 double x = *reinterpret_cast<double *>(&v); 52 ASSERT_MPFR_MATCH(mpfr::Operation::Sqrt, x, __llvm_libc::sqrt(x), 0.5); 53 } 54 } 55 56 TEST(SqrtTest, InDoubleRange) { 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 double x = *reinterpret_cast<double *>(&v); 61 if (isnan(x) || (x < 0)) { 62 continue; 63 } 64 65 ASSERT_MPFR_MATCH(mpfr::Operation::Sqrt, x, __llvm_libc::sqrt(x), 0.5); 66 } 67 } 68