1 //===-- Unittests for cosf ------------------------------------------------===//
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/Array.h"
10 #include "src/__support/FPUtil/FPBits.h"
11 #include "src/math/cosf.h"
12 #include "test/src/math/sdcomp26094.h"
13 #include "utils/MPFRWrapper/MPFRUtils.h"
14 #include "utils/UnitTest/FPMatcher.h"
15 #include "utils/UnitTest/Test.h"
16 #include <math.h>
17 
18 #include <errno.h>
19 #include <stdint.h>
20 
21 using __llvm_libc::testing::sdcomp26094Values;
22 using FPBits = __llvm_libc::fputil::FPBits<float>;
23 
24 namespace mpfr = __llvm_libc::testing::mpfr;
25 
26 DECLARE_SPECIAL_CONSTANTS(float)
27 
28 TEST(LlvmLibcCosfTest, SpecialNumbers) {
29   errno = 0;
30 
31   EXPECT_FP_EQ(aNaN, __llvm_libc::cosf(aNaN));
32   EXPECT_EQ(errno, 0);
33 
34   EXPECT_FP_EQ(1.0f, __llvm_libc::cosf(0.0f));
35   EXPECT_EQ(errno, 0);
36 
37   EXPECT_FP_EQ(1.0f, __llvm_libc::cosf(-0.0f));
38   EXPECT_EQ(errno, 0);
39 
40   errno = 0;
41   EXPECT_FP_EQ(aNaN, __llvm_libc::cosf(inf));
42   EXPECT_EQ(errno, EDOM);
43 
44   errno = 0;
45   EXPECT_FP_EQ(aNaN, __llvm_libc::cosf(neg_inf));
46   EXPECT_EQ(errno, EDOM);
47 }
48 
49 TEST(LlvmLibcCosfTest, InFloatRange) {
50   constexpr uint32_t count = 1000000;
51   constexpr uint32_t step = UINT32_MAX / count;
52   for (uint32_t i = 0, v = 0; i <= count; ++i, v += step) {
53     float x = float(FPBits(v));
54     if (isnan(x) || isinf(x))
55       continue;
56     ASSERT_MPFR_MATCH(mpfr::Operation::Cos, x, __llvm_libc::cosf(x), 1.0);
57   }
58 }
59 
60 // For small values, cos(x) is 1.
61 TEST(LlvmLibcCosfTest, SmallValues) {
62   float x = float(FPBits(0x17800000U));
63   float result = __llvm_libc::cosf(x);
64   EXPECT_MPFR_MATCH(mpfr::Operation::Cos, x, result, 1.0);
65   EXPECT_FP_EQ(1.0f, result);
66 
67   x = float(FPBits(0x0040000U));
68   result = __llvm_libc::cosf(x);
69   EXPECT_MPFR_MATCH(mpfr::Operation::Cos, x, result, 1.0);
70   EXPECT_FP_EQ(1.0f, result);
71 }
72 
73 // SDCOMP-26094: check cosf in the cases for which the range reducer
74 // returns values furthest beyond its nominal upper bound of pi/4.
75 TEST(LlvmLibcCosfTest, SDCOMP_26094) {
76   for (uint32_t v : sdcomp26094Values) {
77     float x = float(FPBits(v));
78     ASSERT_MPFR_MATCH(mpfr::Operation::Cos, x, __llvm_libc::cosf(x), 1.0);
79   }
80 }
81