1 | //===-- Utility class to test sqrt[f|l] -------------------------*- C++ -*-===// |
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/__support/CPP/bit.h" |
10 | #include "test/UnitTest/FEnvSafeTest.h" |
11 | #include "test/UnitTest/FPMatcher.h" |
12 | #include "test/UnitTest/Test.h" |
13 | #include "utils/MPFRWrapper/MPFRUtils.h" |
14 | |
15 | #include "hdr/math_macros.h" |
16 | |
17 | namespace mpfr = LIBC_NAMESPACE::testing::mpfr; |
18 | |
19 | template <typename T> |
20 | class SqrtTest : public LIBC_NAMESPACE::testing::FEnvSafeTest { |
21 | |
22 | DECLARE_SPECIAL_CONSTANTS(T) |
23 | |
24 | static constexpr StorageType HIDDEN_BIT = |
25 | StorageType(1) << LIBC_NAMESPACE::fputil::FPBits<T>::FRACTION_LEN; |
26 | |
27 | public: |
28 | typedef T (*SqrtFunc)(T); |
29 | |
30 | void test_special_numbers(SqrtFunc func) { |
31 | ASSERT_FP_EQ(aNaN, func(aNaN)); |
32 | ASSERT_FP_EQ(inf, func(inf)); |
33 | ASSERT_FP_EQ(aNaN, func(neg_inf)); |
34 | ASSERT_FP_EQ(0.0, func(0.0)); |
35 | ASSERT_FP_EQ(-0.0, func(-0.0)); |
36 | ASSERT_FP_EQ(aNaN, func(T(-1.0))); |
37 | ASSERT_FP_EQ(T(1.0), func(T(1.0))); |
38 | ASSERT_FP_EQ(T(2.0), func(T(4.0))); |
39 | ASSERT_FP_EQ(T(3.0), func(T(9.0))); |
40 | } |
41 | |
42 | void test_denormal_values(SqrtFunc func) { |
43 | for (StorageType mant = 1; mant < HIDDEN_BIT; mant <<= 1) { |
44 | FPBits denormal(T(0.0)); |
45 | denormal.set_mantissa(mant); |
46 | T x = denormal.get_val(); |
47 | EXPECT_MPFR_MATCH_ALL_ROUNDING(mpfr::Operation::Sqrt, x, func(x), 0.5); |
48 | } |
49 | |
50 | constexpr StorageType COUNT = 200'001; |
51 | constexpr StorageType STEP = HIDDEN_BIT / COUNT; |
52 | for (StorageType i = 0, v = 0; i <= COUNT; ++i, v += STEP) { |
53 | T x = LIBC_NAMESPACE::cpp::bit_cast<T>(v); |
54 | EXPECT_MPFR_MATCH_ALL_ROUNDING(mpfr::Operation::Sqrt, x, func(x), 0.5); |
55 | } |
56 | } |
57 | |
58 | void test_normal_range(SqrtFunc func) { |
59 | constexpr StorageType COUNT = 200'001; |
60 | constexpr StorageType STEP = STORAGE_MAX / COUNT; |
61 | for (StorageType i = 0, v = 0; i <= COUNT; ++i, v += STEP) { |
62 | T x = LIBC_NAMESPACE::cpp::bit_cast<T>(v); |
63 | if (isnan(x) || (x < 0)) { |
64 | continue; |
65 | } |
66 | EXPECT_MPFR_MATCH_ALL_ROUNDING(mpfr::Operation::Sqrt, x, func(x), 0.5); |
67 | } |
68 | } |
69 | }; |
70 | |
71 | #define LIST_SQRT_TESTS(T, func) \ |
72 | using LlvmLibcSqrtTest = SqrtTest<T>; \ |
73 | TEST_F(LlvmLibcSqrtTest, SpecialNumbers) { test_special_numbers(&func); } \ |
74 | TEST_F(LlvmLibcSqrtTest, DenormalValues) { test_denormal_values(&func); } \ |
75 | TEST_F(LlvmLibcSqrtTest, NormalRange) { test_normal_range(&func); } |
76 | |