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 "src/math/sqrtf.h"
10 #include "utils/FPUtil/FPBits.h"
11 #include "utils/FPUtil/TestHelpers.h"
12 #include "utils/MPFRWrapper/MPFRUtils.h"
13 #include <math.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 DECLARE_SPECIAL_CONSTANTS(float)
24 
TEST(SqrtfTest,SpecialValues)25 TEST(SqrtfTest, SpecialValues) {
26   ASSERT_FP_EQ(nan, __llvm_libc::sqrtf(nan));
27   ASSERT_FP_EQ(inf, __llvm_libc::sqrtf(inf));
28   ASSERT_FP_EQ(nan, __llvm_libc::sqrtf(negInf));
29   ASSERT_FP_EQ(0.0f, __llvm_libc::sqrtf(0.0f));
30   ASSERT_FP_EQ(-0.0f, __llvm_libc::sqrtf(-0.0f));
31   ASSERT_FP_EQ(nan, __llvm_libc::sqrtf(-1.0f));
32   ASSERT_FP_EQ(1.0f, __llvm_libc::sqrtf(1.0f));
33   ASSERT_FP_EQ(2.0f, __llvm_libc::sqrtf(4.0f));
34   ASSERT_FP_EQ(3.0f, __llvm_libc::sqrtf(9.0f));
35 }
36 
TEST(SqrtfTest,DenormalValues)37 TEST(SqrtfTest, DenormalValues) {
38   for (UIntType mant = 1; mant < HiddenBit; mant <<= 1) {
39     FPBits denormal(0.0f);
40     denormal.mantissa = mant;
41 
42     ASSERT_MPFR_MATCH(mpfr::Operation::Sqrt, float(denormal),
43                       __llvm_libc::sqrtf(denormal), 0.5);
44   }
45 
46   constexpr UIntType count = 1'000'001;
47   constexpr UIntType step = HiddenBit / count;
48   for (UIntType i = 0, v = 0; i <= count; ++i, v += step) {
49     float x = *reinterpret_cast<float *>(&v);
50     ASSERT_MPFR_MATCH(mpfr::Operation::Sqrt, x, __llvm_libc::sqrtf(x), 0.5);
51   }
52 }
53 
TEST(SqrtfTest,InFloatRange)54 TEST(SqrtfTest, InFloatRange) {
55   constexpr UIntType count = 10'000'001;
56   constexpr UIntType step = UIntType(-1) / count;
57   for (UIntType i = 0, v = 0; i <= count; ++i, v += step) {
58     float x = *reinterpret_cast<float *>(&v);
59     if (isnan(x) || (x < 0)) {
60       continue;
61     }
62 
63     ASSERT_MPFR_MATCH(mpfr::Operation::Sqrt, x, __llvm_libc::sqrtf(x), 0.5);
64   }
65 }
66