Created
September 22, 2012 02:23
-
-
Save ivanacostarubio/3764890 to your computer and use it in GitHub Desktop.
Newton's Square Root Approximation
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
| def abs(x) | |
| (x < 0) ? -x : x | |
| end | |
| def sqrtIter(guess, x) | |
| isGoodEnough(guess,x) ? guess : sqrtIter( improve(guess,x) ,x) | |
| end | |
| def isGoodEnough(guess,x) | |
| abs(guess * guess - x) < 0.001 | |
| end | |
| def improve(guess,x) | |
| (guess + x / guess) / 2 | |
| end | |
| def sqrt(x) | |
| sqrtIter(1.0,x) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment