WPILibC++ 2023.4.3-108-ge5452e3
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 square-root function
23 */
24
25#ifndef _gcem_sqrt_HPP
26#define _gcem_sqrt_HPP
27
28namespace internal
29{
30
31template<typename T>
32constexpr
33T
34sqrt_recur(const T x, const T xn, const int count)
35noexcept
36{
37 return( abs(xn - x/xn) / (T(1) + xn) < GCLIM<T>::min() ? \
38 // if
39 xn :
41 // else
42 sqrt_recur(x, T(0.5)*(xn + x/xn), count+1) :
43 xn );
44}
45
46template<typename T>
47constexpr
48T
49sqrt_check(const T x, const T m_val)
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 x :
60 // indistinguishable from zero or one
61 GCLIM<T>::min() > abs(x) ? \
62 T(0) :
63 GCLIM<T>::min() > abs(T(1) - x) ? \
64 x :
65 // else
66 x > T(4) ? \
67 sqrt_check(x/T(4), T(2)*m_val) :
68 m_val * sqrt_recur(x, x/T(2), 0) );
69}
70
71}
72
73
74/**
75 * Compile-time square-root function
76 *
77 * @param x a real-valued input.
78 * @return Computes \f$ \sqrt{x} \f$ using a Newton-Raphson approach.
79 */
80
81template<typename T>
82constexpr
83return_t<T>
84sqrt(const T x)
85noexcept
86{
87 return internal::sqrt_check( static_cast<return_t<T>>(x), return_t<T>(1) );
88}
89
90#endif
constexpr auto count() -> size_t
Definition: core.h:1204
#define GCEM_SQRT_MAX_ITER
Definition: gcem_options.hpp:181
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_posinf(const T x) noexcept
Definition: is_inf.hpp:81
constexpr T sqrt_check(const T x, const T m_val) noexcept
Definition: sqrt.hpp:49
constexpr T sqrt_recur(const T x, const T xn, const int count) noexcept
Definition: sqrt.hpp:34
constexpr bool is_nan(const T x) noexcept
Definition: is_nan.hpp:36
constexpr return_t< T > sqrt(const T x) noexcept
Compile-time square-root function.
Definition: sqrt.hpp:84