First, some codes.
-----------
def calc(n)
(2 ** n) * (5 ** 0.5)
end
puts calc(10000)
=>warning: Bignum out of Float range
-----------
I understand what the problem is.
If I want to get the result, how can I work around the barrier?
Thanks.
Sam
here's some hacky code which returns a 2-element array
the first number is the significant digits and the second number is
the exponent:
def calc(n)
exp=0
val = (2 ** n)
while val*3 > 1e290.to_i
val/=10
exp+=1
end
val *=(5**0.5)
unless val.to_s.grep(/(.*)e\+(.*)/).empty?
val = $1.to_f
exp+=$2.to_i
end
[val, exp]
end
p calc 1
p calc 10
p calc 100
p calc 1000
p calc 10000
[4.47213595499958, 0]
[2289.73360895978, 0]
[2.83455291382873, 30]
[2.39596608414461, 301]
[4.46109674874798, 3010]
-Adam
However, don't believe in too many of these digits...
If you still want to multiply by square roots accurately, it might be a good
idea to look at continued fractions - every square root has a continued
fraction representation that eventually ends in a periodic pattern.
There is an introduction to arithmetic with them at
_http://www.mcs.surrey.ac.uk/Personal/R.Knott/Fibonacci/cfINTRO.html_
(http://www.mcs.surrey.ac.uk/Personal/R.Knott/Fibonacci/cfINTRO.html)
Hope that helps,
Axel
Thank you, Axel.
Actually I came across this problem while reading an article about
fibonacci.
See
http://epsilondelta.wordpress.com/2006/01/29/programming-like-a-mathematician-i-closures/
.
There's a formula for fibonacci and the writer showed 1000000th
fibonacci.
I wanted to calculate it using the formula in Ruby.
I'll read the docs you mentioned.
Thanks.
Sam