Created
May 25, 2021 00:22
-
-
Save jstaursky/891ce79a5271a9984976a125363b189f to your computer and use it in GitHub Desktop.
square root approximation in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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