I’m calculating Fibonacci numbers with binet’s formula and I’m having trouble dividing in ruby. I’ve tried casting numbers to_f etc with no avail. I’ll show you what works and what doesn’t then maybe you can tell me why.
The following doesn’t work
n=5
fib=(1 + sqrt(5))**n - (1-sqrt(5))**n / (2**n * sqrt(5))
puts fib #outputs 354.9257634247335 which is a bunch of garbage
I’ve also tried
n=5
fib=((1 + sqrt(5))**n).to_f - ((1-sqrt(5))**n).to_f / (2**n * sqrt(5)).to_f
puts fib #outputs the exact same thing as above
BUT The following works
n=5
fib1=(1 + sqrt(5))**n - (1-sqrt(5))**n
fib2=(2**n * sqrt(5))
fib = fib1/fib2
puts fib.round(0) #outputs 5 which is correct
Why do the first 2 examples fail but the latter gives me what I want? This is infuriating!
You are missing parenthesis