Skip to content

Instantly share code, notes, and snippets.

@alexshtf
Last active June 7, 2023 11:19
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexshtf/eb5128b3e3e143187794 to your computer and use it in GitHub Desktop.
Save alexshtf/eb5128b3e3e143187794 to your computer and use it in GitHub Desktop.
Constexpr version of c++ square root (for doubles)
#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