consteig
Compile-time eigenvalue and eigenvector computation for C++17
Loading...
Searching...
No Matches
csqrt.hpp
1#ifndef CONSTMATH_CSQRT_HPP
2#define CONSTMATH_CSQRT_HPP
3
4#include "../complex.hpp"
5#include "../math_backend.hpp"
6
7namespace consteig
8{
9
12
22template <typename T> constexpr Complex<T> csqrt(const T x)
23{
24 if (x < static_cast<T>(0))
25 {
26 if constexpr (is_float<T>())
27 {
28 return {static_cast<T>(0), sqrt(abs(x))};
29 }
30 else
31 {
32 // Cast to unsigned long long and negate to safely calculate the
33 // absolute value of x, even if x is INT_MIN or INT64_MIN, avoiding
34 // overflow.
35 return {static_cast<T>(0),
36 static_cast<T>(sqrt(-static_cast<unsigned long long>(x)))};
37 }
38 }
39 else
40 {
41 if constexpr (is_float<T>())
42 {
43 return {sqrt(x), static_cast<T>(0)};
44 }
45 else
46 {
47 return {static_cast<T>(sqrt(static_cast<unsigned long long>(x))),
48 static_cast<T>(0)};
49 }
50 }
51}
52
54
55} // namespace consteig
56
57#endif
constexpr T sqrt(const T x)
Constexpr square root.
Definition sqrt.hpp:67
constexpr Complex< T > csqrt(const T x)
Complex-valued square root of a real number.
Definition csqrt.hpp:22
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
Constexpr complex number type.
Definition complex.hpp:26