Created
February 9, 2012 10:05
-
-
Save kimyoutora/1779001 to your computer and use it in GitHub Desktop.
Square root
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 sqrt(num, precision, beg=0, final=num) | |
final = 1 if num < 1 # handle cases where the squareroot is > num i.e. sqrt(0.1) ~ 0.3 | |
begin | |
guess = (beg + final) / 2.0 | |
diff = num - (guess ** 2) | |
if diff.abs <= precision | |
return guess | |
elsif diff > 0 | |
beg = guess | |
else | |
final = guess | |
end | |
end while diff.abs > precision | |
end | |
def test(num, precision) | |
my_sqrt = sqrt(num, precision) | |
diff = num - (my_sqrt ** 2) | |
puts "num: #{num}, precision: #{precision}, pass? #{diff.abs <= precision}" | |
end | |
test(0, 0.0001) | |
test(0.4, 0.0001) | |
test(1, 0.0001) | |
test(8, 0.0001) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment