WPILibC++ 2023.4.3-108-ge5452e3
cos.hpp
Go to the documentation of this file.
1/*################################################################################
2 ##
3 ## Copyright (C) 2016-2022 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
28namespace internal
29{
30
31template<typename T>
32constexpr
33T
34cos_compute(const T x)
35noexcept
36{
37 return( T(1) - x*x)/(T(1) + x*x );
38}
39
40template<typename T>
41constexpr
42T
43cos_check(const T x)
44noexcept
45{
46 return( // NaN check
47 is_nan(x) ? \
48 GCLIM<T>::quiet_NaN() :
49 // indistinguishable from 0
50 GCLIM<T>::min() > abs(x) ?
51 T(1) :
52 // special cases: pi/2 and pi
53 GCLIM<T>::min() > abs(x - T(GCEM_HALF_PI)) ? \
54 T(0) :
55 GCLIM<T>::min() > abs(x + T(GCEM_HALF_PI)) ? \
56 T(0) :
57 GCLIM<T>::min() > abs(x - T(GCEM_PI)) ? \
58 - T(1) :
59 GCLIM<T>::min() > abs(x + T(GCEM_PI)) ? \
60 - T(1) :
61 // else
62 cos_compute( tan(x/T(2)) ) );
63}
64
65}
66
67/**
68 * Compile-time cosine function
69 *
70 * @param x a real-valued input.
71 * @return the cosine function using \f[ \cos(x) = \frac{1-\tan^2(x/2)}{1+\tan^2(x/2)} \f]
72 */
73
74template<typename T>
75constexpr
76return_t<T>
77cos(const T x)
78noexcept
79{
80 return internal::cos_check( static_cast<return_t<T>>(x) );
81}
82
83#endif
constexpr return_t< T > cos(const T x) noexcept
Compile-time cosine function.
Definition: cos.hpp:77
#define GCEM_PI
Definition: gcem_options.hpp:98
#define GCEM_HALF_PI
Definition: gcem_options.hpp:118
UnitType abs(const UnitType x) noexcept
Compute absolute value.
Definition: math.h:721
constexpr common_t< T1, T2 > min(const T1 x, const T2 y) noexcept
Compile-time pairwise minimum function.
Definition: min.hpp:35
Definition: Eigen_Colamd.h:50
constexpr bool is_nan(const T x) noexcept
Definition: is_nan.hpp:36
constexpr T cos_compute(const T x) noexcept
Definition: cos.hpp:34
constexpr T cos_check(const T x) noexcept
Definition: cos.hpp:43