1//===-- Unittests for log2f -----------------------------------------------===//
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 "hdr/math_macros.h"
10#include "src/__support/FPUtil/FPBits.h"
11#include "src/errno/libc_errno.h"
12#include "src/math/log2f.h"
13#include "test/UnitTest/FPMatcher.h"
14#include "test/UnitTest/Test.h"
15#include "utils/MPFRWrapper/MPFRUtils.h"
16
17#include <stdint.h>
18
19using LlvmLibcLog2fTest = LIBC_NAMESPACE::testing::FPTest<float>;
20
21namespace mpfr = LIBC_NAMESPACE::testing::mpfr;
22
23TEST_F(LlvmLibcLog2fTest, SpecialNumbers) {
24 EXPECT_FP_EQ(aNaN, LIBC_NAMESPACE::log2f(aNaN));
25 EXPECT_FP_EQ(inf, LIBC_NAMESPACE::log2f(inf));
26 EXPECT_FP_IS_NAN_WITH_EXCEPTION(LIBC_NAMESPACE::log2f(neg_inf), FE_INVALID);
27 EXPECT_FP_EQ_WITH_EXCEPTION(neg_inf, LIBC_NAMESPACE::log2f(0.0f),
28 FE_DIVBYZERO);
29 EXPECT_FP_EQ_WITH_EXCEPTION(neg_inf, LIBC_NAMESPACE::log2f(-0.0f),
30 FE_DIVBYZERO);
31 EXPECT_FP_IS_NAN_WITH_EXCEPTION(LIBC_NAMESPACE::log2f(-1.0f), FE_INVALID);
32 EXPECT_FP_EQ_ALL_ROUNDING(zero, LIBC_NAMESPACE::log2f(1.0f));
33}
34
35TEST_F(LlvmLibcLog2fTest, TrickyInputs) {
36 constexpr int N = 10;
37 constexpr uint32_t INPUTS[N] = {
38 0x3f7d57f5U, 0x3f7e3274U, 0x3f7ed848U, 0x3f7fd6ccU, 0x3f7fffffU,
39 0x3f80079bU, 0x3f81d0b5U, 0x3f82e602U, 0x3f83c98dU, 0x3f8cba39U};
40
41 for (int i = 0; i < N; ++i) {
42 float x = FPBits(INPUTS[i]).get_val();
43 EXPECT_MPFR_MATCH_ALL_ROUNDING(mpfr::Operation::Log2, x,
44 LIBC_NAMESPACE::log2f(x), 0.5);
45 }
46}
47
48TEST_F(LlvmLibcLog2fTest, InFloatRange) {
49 constexpr uint32_t COUNT = 100'000;
50 constexpr uint32_t STEP = UINT32_MAX / COUNT;
51 for (uint32_t i = 0, v = 0; i <= COUNT; ++i, v += STEP) {
52 float x = FPBits(v).get_val();
53 if (isnan(x: x) || isinf(x: x))
54 continue;
55 LIBC_NAMESPACE::libc_errno = 0;
56 float result = LIBC_NAMESPACE::log2f(x);
57 // If the computation resulted in an error or did not produce valid result
58 // in the single-precision floating point range, then ignore comparing with
59 // MPFR result as MPFR can still produce valid results because of its
60 // wider precision.
61 if (isnan(x: result) || isinf(x: result) || LIBC_NAMESPACE::libc_errno != 0)
62 continue;
63 ASSERT_MPFR_MATCH_ALL_ROUNDING(mpfr::Operation::Log2, x,
64 LIBC_NAMESPACE::log2f(x), 0.5);
65 }
66}
67

source code of libc/test/src/math/log2f_test.cpp