WPILibC++ 2023.4.3
inv_sqrt.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 inverse-square-root function
23 */
24
25#ifndef _gcem_inv_sqrt_HPP
26#define _gcem_inv_sqrt_HPP
27
28namespace internal
29{
30
31template<typename T>
32constexpr
33T
34inv_sqrt_recur(const T x, const T xn, const int count)
35noexcept
36{
37 return( abs( xn - T(1)/(x*xn) ) / (T(1) + xn) < GCLIM<T>::min() ? \
38 // if
39 xn :
41 // else
42 inv_sqrt_recur(x, T(0.5)*(xn + T(1)/(x*xn)), count+1) :
43 xn );
44}
45
46template<typename T>
47constexpr
48T
50noexcept
51{
52 return( is_nan(x) ? \
53 GCLIM<T>::quiet_NaN() :
54 //
55 x < T(0) ? \
56 GCLIM<T>::quiet_NaN() :
57 //
58 is_posinf(x) ? \
59 T(0) :
60 // indistinguishable from zero or one
61 GCLIM<T>::min() > abs(x) ? \
62 GCLIM<T>::infinity() :
63 GCLIM<T>::min() > abs(T(1) - x) ? \
64 x :
65 // else
66 inv_sqrt_recur(x, x/T(2), 0) );
67}
68
69}
70
71
72/**
73 * Compile-time inverse-square-root function
74 *
75 * @param x a real-valued input.
76 * @return Computes \f$ 1 / \sqrt{x} \f$ using a Newton-Raphson approach.
77 */
78
79template<typename T>
80constexpr
81return_t<T>
82inv_sqrt(const T x)
83noexcept
84{
85 return internal::inv_sqrt_check( static_cast<return_t<T>>(x) );
86}
87
88#endif
constexpr auto count() -> size_t
Definition: core.h:1204
#define GCEM_INV_SQRT_MAX_ITER
Definition: gcem_options.hpp:185
UnitType abs(const UnitType x) noexcept
Compute absolute value.
Definition: math.h:721
constexpr return_t< T > inv_sqrt(const T x) noexcept
Compile-time inverse-square-root function.
Definition: inv_sqrt.hpp:82
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_posinf(const T x) noexcept
Definition: is_inf.hpp:81
constexpr bool is_nan(const T x) noexcept
Definition: is_nan.hpp:36
constexpr T inv_sqrt_check(const T x) noexcept
Definition: inv_sqrt.hpp:49
constexpr T inv_sqrt_recur(const T x, const T xn, const int count) noexcept
Definition: inv_sqrt.hpp:34