Work around for "Bignum out of Float range"?

S

Sam Kong

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
 
A

Adam Shelly

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=3D0
val =3D (2 ** n)
while val*3 > 1e290.to_i
val/=3D10
exp+=3D1
end
val *=3D(5**0.5)
unless val.to_s.grep(/(.*)e\+(.*)/).empty?
val =3D $1.to_f
exp+=3D$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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,000
Messages
2,570,252
Members
46,848
Latest member
CristineKo

Latest Threads

Top