Skip to content

Instantly share code, notes, and snippets.

@agargiulo
Last active October 3, 2016 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agargiulo/4b11fa76b4b04f9ae4f1 to your computer and use it in GitHub Desktop.
Save agargiulo/4b11fa76b4b04f9ae4f1 to your computer and use it in GitHub Desktop.
Heron square root implementations in a few languages.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
double heron_sqrt(long n, double percision);
void compare_sqrt(long n);
int main(int argc, char **argv)
{
if (argc < 2)
{
fprintf(stderr, "Usage: %s n\nn - number to find the square root of\n", argv[0]);
return(EXIT_FAILURE);
}
long n = strtol(argv[1], NULL, 10);
compare_sqrt(n);
return(EXIT_SUCCESS);
}
double heron_sqrt(long n, double percision)
{
if (n == 0)
{
return 0.0;
}
double guess = n / 3.0;
while (true)
{
double lastGuess = guess;
guess = (guess + (n / guess)) / 2.0;
if (abs(lastGuess - guess) <= percision) break;
}
return guess;
}
void compare_sqrt(long n)
{
double percision = 0.000000000001;
double heron = heron_sqrt(n, percision);
double real_sqrt = sqrt(n);
if (heron == real_sqrt)
{
printf("The square root of %ld is %f\n", n, heron);
} else
{
printf(
"The square root of %ld using heron (%f) differs by %f\n",
n,
heron,
heron - real_sqrt
);
}
}
#!/usr/bin/python2
import math
import sys
def heron_sqrt(n, percision=0.000000000001):
if n == 0:
return 0
guess = n / 3.0
while True:
lastguess = guess
guess = (guess + (n / guess)) / 2.0
if abs(lastguess - guess) <= percision:
break
return guess
def compare_sqrt(n, percision=0.000000000001):
heron = heron_sqrt(n, percision)
py_sqrt = math.sqrt(n)
if heron == py_sqrt:
print "The sqrt of {0} is {1}".format(n, heron)
else:
print "The sqrt of {0} using heron ({1}) differs by {2}".format(
n,heron, heron - py_sqrt
)
if __name__ == "__main__":
if len(sys.argv) > 1:
compare_sqrt(int(sys.argv[1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment