Last active
September 17, 2024 08:59
-
-
Save alexshtf/eb5128b3e3e143187794 to your computer and use it in GitHub Desktop.
Constexpr version of c++ square root (for doubles)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <limits> | |
namespace Detail | |
{ | |
double constexpr sqrtNewtonRaphson(double x, double curr, double prev) | |
{ | |
return curr == prev | |
? curr | |
: sqrtNewtonRaphson(x, 0.5 * (curr + x / curr), curr); | |
} | |
} | |
/* | |
* Constexpr version of the square root | |
* Return value: | |
* - For a finite and non-negative value of "x", returns an approximation for the square root of "x" | |
* - Otherwise, returns NaN | |
*/ | |
double constexpr sqrt(double x) | |
{ | |
return x >= 0 && x < std::numeric_limits<double>::infinity() | |
? Detail::sqrtNewtonRaphson(x, x, 0) | |
: std::numeric_limits<double>::quiet_NaN(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment