Skip to content

Instantly share code, notes, and snippets.

@hamsham
Created November 15, 2015 08:46
Show Gist options
  • Save hamsham/c088b876df888bdeafb7 to your computer and use it in GitHub Desktop.
Save hamsham/c088b876df888bdeafb7 to your computer and use it in GitHub Desktop.
Newton's method for approximating square roots.
/*
* Testing a simple square-root method.
*
* g++ -std=c++11 -Wall -Werror -Wextra -pedantic -pedantic-errors root.cpp -o root
*/
#include <iostream>
static constexpr double EPSILON = 1.0e-9;
template <typename num_t>
num_t root(num_t n, num_t precision = EPSILON) {
if (n == num_t{0}) {
return num_t{0};
}
num_t guess = n / num_t{3};
while (true) {
const num_t lastGuess = guess;
guess = (guess + (n/guess)) / num_t{2};
if (std::abs(lastGuess-guess) <= precision) {
break;
}
}
return guess;
}
int main() {
std::cout << "Sqrt 49: " << root(49) << std::endl;
std::cout << "Sqrt 36: " << root(36) << std::endl;
std::cout << "Sqrt 100: " << root(100) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment