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