Last active
September 29, 2016 12:40
-
-
Save ugofred/f34f1bedcf72ca0c37a83aeaada4ec9d to your computer and use it in GitHub Desktop.
Code for finding the square root of a number
This file contains 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
[1] pry(main)> def square(n, diff) | |
[1] pry(main)* guess = refine(1, n) | |
[1] pry(main)* while (((guess * guess) - n ) .abs > diff) | |
[1] pry(main)* guess = refine(guess, n) | |
[1] pry(main)* end | |
[1] pry(main)* puts guess | |
[1] pry(main)* end | |
=> :square | |
[2] pry(main)> def refine(guess, n) | |
[2] pry(main)* guess = (guess + (n / guess)) / 2.0 | |
[2] pry(main)* end | |
=> :refine | |
[3] pry(main)> square(2, 0.000001) | |
1.4142135623746899 | |
=> nil | |
[4] pry(main)> | |
=> nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment