1 /*
2 * Single-precision cos function.
3 *
4 * Copyright (c) 2018-2024, Arm Limited.
5 * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception
6 */
7
8 #include <stdint.h>
9 #include <math.h>
10 #include "math_config.h"
11 #include "sincosf.h"
12 #include "test_defs.h"
13 #include "test_sig.h"
14
15 /* Fast cosf implementation. Worst-case ULP is 0.5607, maximum relative
16 error is 0.5303 * 2^-23. A single-step range reduction is used for
17 small values. Large inputs have their range reduced using fast integer
18 arithmetic. */
19 float
cosf(float y)20 cosf (float y)
21 {
22 double x = y;
23 double s;
24 int n;
25 const sincos_t *p = &__sincosf_table[0];
26
27 if (abstop12 (y) < abstop12 (pio4f))
28 {
29 double x2 = x * x;
30
31 if (unlikely (abstop12 (y) < abstop12 (0x1p-12f)))
32 return 1.0f;
33
34 return sinf_poly (x, x2, p, 1);
35 }
36 else if (likely (abstop12 (y) < abstop12 (120.0f)))
37 {
38 x = reduce_fast (x, p, &n);
39
40 /* Setup the signs for sin and cos. */
41 s = p->sign[n & 3];
42
43 if (n & 2)
44 p = &__sincosf_table[1];
45
46 return sinf_poly (x * s, x * x, p, n ^ 1);
47 }
48 else if (abstop12 (y) < abstop12 (INFINITY))
49 {
50 uint32_t xi = asuint (y);
51 int sign = xi >> 31;
52
53 x = reduce_large (xi, &n);
54
55 /* Setup signs for sin and cos - include original sign. */
56 s = p->sign[(n + sign) & 3];
57
58 if ((n + sign) & 2)
59 p = &__sincosf_table[1];
60
61 return sinf_poly (x * s, x * x, p, n ^ 1);
62 }
63 else
64 return __math_invalidf (y);
65 }
66
67 TEST_SIG (S, F, 1, cos, -3.1, 3.1)
68 TEST_ULP (cosf, 0.06)
69 TEST_ULP_NONNEAREST (cosf, 0.5)
70 TEST_INTERVAL (cosf, 0, 0xffff0000, 10000)
71 TEST_SYM_INTERVAL (cosf, 0x1p-14, 0x1p54, 50000)
72