1 //===-- Unittests for fmax -----------------------------------------------===//
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 "include/math.h"
10 #include "src/math/fmax.h"
11 #include "utils/FPUtil/FPBits.h"
12 #include "utils/FPUtil/TestHelpers.h"
13 #include "utils/UnitTest/Test.h"
14 
15 using FPBits = __llvm_libc::fputil::FPBits<double>;
16 
17 double nan = FPBits::buildNaN(1);
18 double inf = FPBits::inf();
19 double negInf = FPBits::negInf();
20 
21 TEST(FmaxTest, NaNArg) {
22   EXPECT_FP_EQ(inf, __llvm_libc::fmax(nan, inf));
23   EXPECT_FP_EQ(negInf, __llvm_libc::fmax(negInf, nan));
24   EXPECT_FP_EQ(0.0, __llvm_libc::fmax(nan, 0.0));
25   EXPECT_FP_EQ(-0.0, __llvm_libc::fmax(-0.0, nan));
26   EXPECT_FP_EQ(-1.2345, __llvm_libc::fmax(nan, -1.2345));
27   EXPECT_FP_EQ(1.2345, __llvm_libc::fmax(1.2345, nan));
28   EXPECT_NE(isnan(__llvm_libc::fmax(nan, nan)), 0);
29 }
30 
31 TEST(FmaxTest, InfArg) {
32   EXPECT_FP_EQ(inf, __llvm_libc::fmax(negInf, inf));
33   EXPECT_FP_EQ(inf, __llvm_libc::fmax(inf, 0.0));
34   EXPECT_FP_EQ(inf, __llvm_libc::fmax(-0.0, inf));
35   EXPECT_FP_EQ(inf, __llvm_libc::fmax(inf, 1.2345));
36   EXPECT_FP_EQ(inf, __llvm_libc::fmax(-1.2345, inf));
37 }
38 
39 TEST(FmaxTest, NegInfArg) {
40   EXPECT_FP_EQ(inf, __llvm_libc::fmax(inf, negInf));
41   EXPECT_FP_EQ(0.0, __llvm_libc::fmax(negInf, 0.0));
42   EXPECT_FP_EQ(-0.0, __llvm_libc::fmax(-0.0, negInf));
43   EXPECT_FP_EQ(-1.2345, __llvm_libc::fmax(negInf, -1.2345));
44   EXPECT_FP_EQ(1.2345, __llvm_libc::fmax(1.2345, negInf));
45 }
46 
47 TEST(FmaxTest, BothZero) {
48   EXPECT_FP_EQ(0.0, __llvm_libc::fmax(0.0, 0.0));
49   EXPECT_FP_EQ(0.0, __llvm_libc::fmax(-0.0, 0.0));
50   EXPECT_FP_EQ(0.0, __llvm_libc::fmax(0.0, -0.0));
51   EXPECT_FP_EQ(-0.0, __llvm_libc::fmax(-0.0, -0.0));
52 }
53 
54 TEST(FmaxTest, InDoubleRange) {
55   using UIntType = FPBits::UIntType;
56   constexpr UIntType count = 10000001;
57   constexpr UIntType step = UIntType(-1) / count;
58   for (UIntType i = 0, v = 0, w = UIntType(-1); i <= count;
59        ++i, v += step, w -= step) {
60     double x = FPBits(v), y = FPBits(w);
61     if (isnan(x) || isinf(x))
62       continue;
63     if (isnan(y) || isinf(y))
64       continue;
65     if ((x == 0) && (y == 0))
66       continue;
67 
68     if (x > y) {
69       EXPECT_FP_EQ(x, __llvm_libc::fmax(x, y));
70     } else {
71       EXPECT_FP_EQ(y, __llvm_libc::fmax(x, y));
72     }
73   }
74 }
75