Skip to content

Instantly share code, notes, and snippets.

@jsundram
Created November 5, 2011 16:19
Show Gist options
  • Select an option

  • Save jsundram/1341720 to your computer and use it in GitHub Desktop.

Select an option

Save jsundram/1341720 to your computer and use it in GitHub Desktop.
Newton-Raphson square root implementation
double root_NR(double n, double epsilon=.0000000001)
{
if (n < 0) return 0.0; // throw?
// http://mathworld.wolfram.com/SquareRootAlgorithms.html
// Both Bhaskara-Brouncker and Newton's iteration use
// (1 + n) / 2 instead of just guessing n/2.
double r = 0.5 + 0.5 * n;
double f = r*r - n;
while (epsilon < abs(f))
{
printf("%2.9f\n", r);
r -= 0.5 * f / r;
f = r*r - n;
}
return r;
}
int main()
{
double epsilon = .0000000001;
double n = 2.0;
printf("root_NR(%f) == %2.9f\n", n, root_NR(n, epsilon));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment