Created
November 5, 2011 16:19
-
-
Save jsundram/1341720 to your computer and use it in GitHub Desktop.
Newton-Raphson square root implementation
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
| 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