consteig
Compile-time eigenvalue and eigenvector computation for C++17
Loading...
Searching...
No Matches
sqrt.hpp
1#ifndef CONSTMATH_SQRT_HPP
2#define CONSTMATH_SQRT_HPP
3
4#include "../../consteig_options.hpp"
5#include "abs.hpp"
6#include "utilities.hpp"
7
8namespace consteig
9{
10
13
14template <typename T>
15constexpr T sqrt_recur(const T x, const T xn, const int count)
16{
17 return (abs(xn - x / xn) / (T(1) + xn) < epsilon<T>() ? xn
19 ? sqrt_recur(x, T(0.5) * (xn + x / xn), count + 1)
20 : xn);
21}
22
23template <typename T> constexpr T sqrt_check(const T x, const T m_val)
24{
25 return (x == T(0) ? T(0)
26 : epsilon<T>() > abs(T(1) - x) ? x
27 : x > T(4) ? sqrt_check(x / T(4), T(2) * m_val)
28 : x < T(0.25) ? sqrt_check(x * T(4), m_val / T(2))
29 : m_val * sqrt_recur(x, x / T(2), 0));
30}
31
32template <typename T> constexpr T sqrt_int(const T x)
33{
34 // The closed guess will be stored in the root
35 T root{static_cast<T>(0)};
36
37 // Base cases
38 if (x == 0 || x == 1)
39 {
40 root = x;
41 }
42 else
43 {
44 // Starting from 1, try all numbers until
45 // i is greater than x / i (avoids i*i overflow).
46 T i = 1;
47 while (i <= x / i)
48 {
49 i++;
50 }
51 root = i - 1;
52 }
53
54 return root;
55}
56
67template <typename T> constexpr T sqrt(const T x)
68{
69 // Users should call csqrt(x) if x might be negative.
70 if (x < static_cast<T>(0))
71 {
72 // We return a poison value (-1) as constexpr NaN is not portably
73 // supported in C++17 without built-ins. In the future, this could
74 // be replaced with a real NaN if a portable constexpr solution is
75 // found.
76 return poison_nan<T>();
77 }
78
79 if constexpr (is_float<T>())
80 {
81 return sqrt_check(x, static_cast<T>(1));
82 }
83 else
84 {
85 return sqrt_int(x);
86 }
87}
88
90
91} // namespace consteig
92
93#endif
#define CONSTEIG_MAX_ITER
Maximum QR iterations per eigenvalue block.
Definition consteig_options.hpp:21
constexpr T sqrt(const T x)
Constexpr square root.
Definition sqrt.hpp:67
constexpr T abs(const T x)
Absolute value of a real number.
Definition abs.hpp:17
constexpr T epsilon()
Machine epsilon for type T.
Definition utilities.hpp:82