Skip to content

Instantly share code, notes, and snippets.

@alexshtf
Last active September 17, 2024 08:59
Show Gist options
  • 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