1 | //===-- Utility class to test integer sqrt ----------------------*- 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 "test/UnitTest/FPMatcher.h" |
10 | #include "test/UnitTest/Test.h" |
11 | |
12 | #include "src/__support/CPP/bit.h" |
13 | #include "src/__support/FPUtil/BasicOperations.h" |
14 | #include "src/__support/FPUtil/sqrt.h" |
15 | #include "src/__support/fixed_point/fx_rep.h" |
16 | #include "src/__support/fixed_point/sqrt.h" |
17 | |
18 | template <typename T> class ISqrtTest : public LIBC_NAMESPACE::testing::Test { |
19 | |
20 | using OutType = |
21 | typename LIBC_NAMESPACE::fixed_point::internal::SqrtConfig<T>::OutType; |
22 | using FXRep = LIBC_NAMESPACE::fixed_point::FXRep<OutType>; |
23 | static constexpr OutType zero = FXRep::ZERO(); |
24 | static constexpr OutType one = static_cast<OutType>(1); |
25 | static constexpr OutType eps = FXRep::EPS(); |
26 | |
27 | public: |
28 | typedef OutType (*SqrtFunc)(T); |
29 | |
30 | void testSpecialNumbers(SqrtFunc func) { |
31 | EXPECT_EQ(zero, func(T(0))); |
32 | |
33 | EXPECT_EQ(one, func(T(1))); |
34 | EXPECT_EQ(static_cast<OutType>(2.0), func(T(4))); |
35 | EXPECT_EQ(static_cast<OutType>(4.0), func(T(16))); |
36 | EXPECT_EQ(static_cast<OutType>(16.0), func(T(256))); |
37 | |
38 | constexpr int COUNT = 255; |
39 | constexpr double ERR = 3.0 * static_cast<double>(eps); |
40 | double x_d = 0.0; |
41 | T x = 0; |
42 | for (int i = 0; i < COUNT; ++i) { |
43 | x_d += 1.0; |
44 | ++x; |
45 | double y_d = static_cast<double>(func(x)); |
46 | double result = LIBC_NAMESPACE::fputil::sqrt(x: x_d); |
47 | double errors = LIBC_NAMESPACE::fputil::abs(x: (y_d / result) - 1.0); |
48 | if (errors > ERR) { |
49 | // Print out the failure input and output. |
50 | EXPECT_EQ(x, T(0)); |
51 | EXPECT_EQ(func(x), zero); |
52 | } |
53 | ASSERT_TRUE(errors <= ERR); |
54 | } |
55 | } |
56 | }; |
57 | |
58 | #define LIST_ISQRT_TESTS(Name, T, func) \ |
59 | using LlvmLibcISqrt##Name##Test = ISqrtTest<T>; \ |
60 | TEST_F(LlvmLibcISqrt##Name##Test, SpecialNumbers) { \ |
61 | testSpecialNumbers(&func); \ |
62 | } \ |
63 | static_assert(true, "Require semicolon.") |
64 | |