Skip to content

Instantly share code, notes, and snippets.

@ugofred
Last active September 29, 2016 12:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ugofred/f34f1bedcf72ca0c37a83aeaada4ec9d to your computer and use it in GitHub Desktop.
Save ugofred/f34f1bedcf72ca0c37a83aeaada4ec9d to your computer and use it in GitHub Desktop.
Code for finding the square root of a number
[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