WPILibC++ 2024.3.2
cos.hpp
Go to the documentation of this file.
1/*################################################################################
2 ##
3 ## Copyright (C) 2016-2023 Keith O'Hara
4 ##
5 ## This file is part of the GCE-Math C++ library.
6 ##
7 ## Licensed under the Apache License, Version 2.0 (the "License");
8 ## you may not use this file except in compliance with the License.
9 ## You may obtain a copy of the License at
10 ##
11 ## http://www.apache.org/licenses/LICENSE-2.0
12 ##
13 ## Unless required by applicable law or agreed to in writing, software
14 ## distributed under the License is distributed on an "AS IS" BASIS,
15 ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 ## See the License for the specific language governing permissions and
17 ## limitations under the License.
18 ##
19 ################################################################################*/
20
21/*
22 * compile-time cosine function using tan(x/2)
23 */
24
25#ifndef _gcem_cos_HPP
26#define _gcem_cos_HPP
27
28#include <cmath>
29#include <type_traits>
30
31namespace gcem
32{
33
34namespace internal
35{
36
37template<typename T>
38constexpr
39T
40cos_compute(const T x)
41noexcept
42{
43 return( T(1) - x*x)/(T(1) + x*x );
44}
45
46template<typename T>
47constexpr
48T
49cos_check(const T x)
50noexcept
51{
52 return( // NaN check
53 is_nan(x) ? \
55 // indistinguishable from 0
56 GCLIM<T>::min() > abs(x) ?
57 T(1) :
58 // special cases: pi/2 and pi
59 GCLIM<T>::min() > abs(x - T(GCEM_HALF_PI)) ? \
60 T(0) :
61 GCLIM<T>::min() > abs(x + T(GCEM_HALF_PI)) ? \
62 T(0) :
63 GCLIM<T>::min() > abs(x - T(GCEM_PI)) ? \
64 - T(1) :
65 GCLIM<T>::min() > abs(x + T(GCEM_PI)) ? \
66 - T(1) :
67 // else
68 cos_compute( tan(x/T(2)) ) );
69}
70
71}
72
73/**
74 * Compile-time cosine function
75 *
76 * @param x a real-valued input.
77 * @return the cosine function using \f[ \cos(x) = \frac{1-\tan^2(x/2)}{1+\tan^2(x/2)} \f]
78 */
79
80template<typename T>
81constexpr
82return_t<T>
83cos(const T x)
84noexcept
85{
87 return internal::cos_check( static_cast<return_t<T>>(x) );
88 } else {
89 return std::cos(x);
90 }
91}
92
93}
94
95#endif
#define GCEM_PI
Definition: gcem_options.hpp:98
#define GCEM_HALF_PI
Definition: gcem_options.hpp:118
constexpr FMT_INLINE auto is_constant_evaluated(bool default_value=false) noexcept -> bool
Definition: core.h:304
constexpr T cos_compute(const T x) noexcept
Definition: cos.hpp:40
constexpr bool is_nan(const T x) noexcept
Definition: is_nan.hpp:39
constexpr T cos_check(const T x) noexcept
Definition: cos.hpp:49
Definition: is_even.hpp:29
constexpr T abs(const T x) noexcept
Compile-time absolute value function.
Definition: abs.hpp:40
constexpr return_t< T > cos(const T x) noexcept
Compile-time cosine function.
Definition: cos.hpp:83
std::numeric_limits< T > GCLIM
Definition: gcem_options.hpp:74
typename std::conditional< std::is_integral< T >::value, double, T >::type return_t
Definition: gcem_options.hpp:77