Skip to content

Instantly share code, notes, and snippets.

@jsundram
Created January 28, 2011 03:11
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 jsundram/799762 to your computer and use it in GitHub Desktop.
Save jsundram/799762 to your computer and use it in GitHub Desktop.
float root(float n, float epsilon=.000001f)
{
if (n <= 0.0f)
return 0.0f;
float guess = n/2.1f;
float error = n - guess*guess;
while (epsilon < fabs(error))
{
guess += error / 2;
error = n - guess*guess;
}
return guess;
}
int main()
{
float n = 2;
float a = sqrt(n);
float b = root(n, e);
fprintf(stdout, "sqrt(%f) = %2.9f\n", n, a);
fprintf(stdout, "root(%f) = %2.9f (precision: %2.9f)\n", n, b, e);
fprintf(stdout, "delta: %2.9f, epsilon: %2.9f\n", fabs(b-a), e);
return 1;
}
@jsundram
Copy link
Author

newton > babylon

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment