tags:

views:

213

answers:

1

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 the warning

Bignum out of Float range

How can I fixed my code to solve this error?

Since ruby is dynamically typed, I don't know how. Thanks a lot.

+2  A: 

What you're looking for is BigDecimal.


Something like this may work (I let it run for a minute on my machine and it still hadn't come up with an answer... seems to 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
fiXedd