AutoPas  3.0.0
Loading...
Searching...
No Matches
ConstexprMath.h
Go to the documentation of this file.
1
8#pragma once
9
10#include <limits>
11
12namespace autopas::utils::ConstexprMath {
13
21template <typename T>
22constexpr typename std::enable_if_t<std::is_floating_point_v<T>, T> sqrt(T x, T epsilon) {
23 if (x >= 0 and x < std::numeric_limits<T>::infinity()) {
24 T xn = x;
25 T prev = 0;
26 // the while loop checks if the absolut value of (xn - prev) is greater as the specified epsilon
27 while ((xn - prev < 0 ? prev - xn : xn - prev) > epsilon) {
28 prev = xn;
29 T xn1 = 0.5 * (xn + x / xn);
30 xn = xn1;
31 }
32 return xn;
33 } else {
34 return std::numeric_limits<T>::quiet_NaN();
35 }
36}
37
44template <typename T>
45constexpr typename std::enable_if_t<std::is_integral_v<T>, T> sqrt(T x) {
46 // see https://en.wikipedia.org/wiki/Integer_square_root#Example_implementation_in_C
47 if (x >= 0) {
48 if (x <= 1) {
49 return x;
50 }
51 T x0 = x / 2;
52 T x1 = (x0 + x / x0) / 2;
53 while (x1 < x0) {
54 x0 = x1;
55 x1 = (x0 + x / x0) / 2;
56 }
57 return x0;
58 } else {
59 throw std::invalid_argument("Negative number passed.");
60 }
61}
62
63} // namespace autopas::utils::ConstexprMath
constexpr std::enable_if_t< std::is_floating_point_v< T >, T > sqrt(T x, T epsilon)
Calculates the square root of floating point values x based on Newton-Raphson methon.
Definition: ConstexprMath.h:22