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