So I’m aware of the Math.sqrt(number) method in Ruby, but as part of learning the language I thought it’d be a good idea to make some simple functions. I could be going about finding the square root wrong from a fundamental level, but here’s what I did:
def negative?(number)
number < 0
end
@start = 2
def sqrt(number)
if negative? number
puts "Can't do negative"
else
if @start**2 < number
@start += 0.01
sqrt(number)
else
puts "Square root of #{number} is #{@start}!"
end
end
end
def start_sqrt
print "Input text: "
number = Integer(gets.strip)
sqrt(number)
end
begin
start_sqrt
rescue ArgumentError
puts "Need a positive number!"
end
This works fine for smaller numbers, but when I get to entering larger numbers I need to change the value of @start if I want to get an answer, otherwise it says “stack too deep”. Is there something wrong I’m doing in the code, or is Ruby doing everything fine and I just am asking it to find the square root of a number in a resource-intensive way? I guess this is maybe even less of a programming question and more of a math question, cause I know I could just do:
def sqrt(number)
if negative? number
puts "Can't do negative"
else
root = number**0.5
puts "Square root of #{number} is #{root}!"
end
end
It looks like Ruby is working as expected. You are asking it to find the square root of a number in a resource-intensive way (recursion).
In fact, you have created a stack overflow error. 🙂