How do I resolve the "Bignum out of Float range" warning?
Running this code:
n = 4 * 1000 * 1000
fn = (((1 + Math.sqrt(5)) ** n) - ((1 - Math.sqrt(5)) ** n)) / ((2 ** n) * Math.sqrt(5))
puts fn - 1
I get a warning
Bignum out of Float range
How can I fix my code to resolve this error?
Since ruby is dynamically typed, I don't know how to do this. Many thanks.
0
a source to share
1 answer
What you are looking for is BigDecimal .
Something like this might work (I let it run for a minute on my machine and it still hasn't come up with an answer ... seems computationally expensive):
require "bigdecimal"
n = (4 * 1000 * 1000)
sqr_5 = BigDecimal("5.0").sqrt(5)
sqr_5a1 = BigDecimal((1+sqr_5).to_s)
sqr_5m1 = BigDecimal((sqr_5-1).to_s)
fn = (sqr_5a1.power(n) - (sqr_5m1.power(n))) / ((2.power(n)) * sqr_5)
puts fn - 1
+3
a source to share