Revert "[libc] Use best-fit binary trie to make malloc logarithmic" (#117065)
[llvm-project.git] / libc / test / src / stdfix / SqrtTest.h
blob2a8a825abb460ca970bdbcedff870869b5e81e04
1 //===-- Utility class to test fixed-point 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 //===----------------------------------------------------------------------===//
9 #include "test/UnitTest/Test.h"
11 #include "src/__support/CPP/bit.h"
12 #include "src/__support/FPUtil/BasicOperations.h"
13 #include "src/__support/FPUtil/sqrt.h"
14 #include "src/__support/fixed_point/fx_rep.h"
15 #include "src/__support/fixed_point/sqrt.h"
17 template <typename T> class SqrtTest : public LIBC_NAMESPACE::testing::Test {
19 using FXRep = LIBC_NAMESPACE::fixed_point::FXRep<T>;
20 static constexpr T zero = FXRep::ZERO();
21 static constexpr T min = FXRep::MIN();
22 static constexpr T max = FXRep::MAX();
23 static constexpr T half = static_cast<T>(0.5);
24 static constexpr T quarter = static_cast<T>(0.25);
25 static constexpr T one =
26 (FXRep::INTEGRAL_LEN > 0) ? static_cast<T>(1) : FXRep::MAX();
27 static constexpr T eps = FXRep::EPS();
29 public:
30 typedef T (*SqrtFunc)(T);
32 void testSpecialNumbers(SqrtFunc func) {
33 EXPECT_EQ(zero, func(zero));
34 EXPECT_EQ(half, func(quarter));
36 if constexpr (FXRep::INTEGRAL_LEN) {
37 EXPECT_EQ(one, func(one));
38 EXPECT_EQ(static_cast<T>(2.0), func(static_cast<T>(4.0)));
41 using StorageType = typename FXRep::StorageType;
43 constexpr size_t COUNT = 255;
44 constexpr StorageType STEP =
45 StorageType(~StorageType(0)) / static_cast<StorageType>(COUNT);
46 constexpr double ERR = 3.0 * static_cast<double>(eps);
47 StorageType x = 0;
48 for (size_t i = 0; i < COUNT; ++i, x += STEP) {
49 T v = LIBC_NAMESPACE::cpp::bit_cast<T>(x);
50 double v_d = static_cast<double>(v);
51 double errors = LIBC_NAMESPACE::fputil::abs(
52 static_cast<double>(func(v)) -
53 LIBC_NAMESPACE::fputil::sqrt<double>(v_d));
54 if (errors > ERR) {
55 // Print out the failure input and output.
56 EXPECT_EQ(v, zero);
57 EXPECT_EQ(func(v), zero);
59 ASSERT_TRUE(errors <= ERR);
64 #define LIST_SQRT_TESTS(T, func) \
65 using LlvmLibcSqrtTest = SqrtTest<T>; \
66 TEST_F(LlvmLibcSqrtTest, SpecialNumbers) { testSpecialNumbers(&func); } \
67 static_assert(true, "Require semicolon.")