Skip to content

Instantly share code, notes, and snippets.

@jstaursky
Created May 25, 2021 00:22
Show Gist options
  • Save jstaursky/891ce79a5271a9984976a125363b189f to your computer and use it in GitHub Desktop.
Save jstaursky/891ce79a5271a9984976a125363b189f to your computer and use it in GitHub Desktop.
square root approximation in C
// Note: sqrt -- approximate method for calculating the square root of a number.
double sqrt (double num)
{
double start = 0.0;
double epsilon = 0.1; // Accuracy granularity.
// Find nearest perfect square.
while ((num - start * start) > 0)
start += 1;
// Calculate the avg of the difference between successive estimates until
// the value is less than epsilon.
// Method relies on the fact that if ab=n and a < sqrt(n), then b has to be
// greater than sqrt(n).
// Since 'start' is a guess that is less than sqrt(n), it must be that
// (n / start) > sqrt(n) -- b/c (n / start) * start = n
// (that is, n = ab and a = start, and b = n / start).
double approx, estimate = start;
while (approx = ((estimate + (num / estimate)) / 2), approx - estimate > epsilon)
estimate = approx;
return approx;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment