Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Work around for "Bignum out of Float range"?

19 views
Skip to first unread message

Sam Kong

unread,
Feb 2, 2006, 1:27:13 PM2/2/06
to
Hi!

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

Adam Shelly

unread,
Feb 2, 2006, 2:31:47 PM2/2/06
to
On 2/2/06, Sam Kong <sam.s...@gmail.com> wrote:
> If I want to get the result, how can I work around the barrier?

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


Nura...@aol.com

unread,
Feb 2, 2006, 2:34:51 PM2/2/06
to
Dear Sam,

your problem is somewhat insolvable, since the square root of 5 has
an infinite number of digits, so it cannot be represented correctly
on any computer (in decimal or binary notation).
For arbitrary precision calculations with Fixnum exponents, there's
bigdecimal.

require "bigdecimal"

def calc(n,prec)
# prec is the precision of the sqrt calculations
res=(BigDecimal.new("2") ** n)*BigDecimal("5").sqrt(prec)
end




puts calc(10000) => 0.44610[several lines of digits]*10^3011 (for prec=10)


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

Sam Kong

unread,
Feb 2, 2006, 6:19:43 PM2/2/06
to

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

0 new messages