0

I use Ruby 2.2.3 and Rails 4.2.3. I get an NoMemoryError: failed to allocate memory using the following code in irb console:

# Using 123e+1000000000000000000
BigDecimal('123e+1000000000000000000').to_s
#=> NoMemoryError: failed to allocate memory

But this example with a more bigger number works:

# Using 123e+1000000000000000000000000000000000
BigDecimal('123e+1000000000000000000000000000000000').to_s
#=> "Infinity"

Here the code of BigDecimal: https://github.com/rails/rails/blob/v4.2.3/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb

phlegx
  • 2,618
  • 3
  • 35
  • 39

2 Answers2

2

The fact that you run out of memory is nothing strange. The number 123e+1000000000000000000 has a quintillion zeroes. Representing it as a string would take a quintillion characters.

At one byte per character, you're looking at (roughly) 10^18 bytes, 10^15 kilobytes, 10^12 megabytes, or 10^9 gigabytes. So unless you have in the range of a billion gigabytes of RAM, it's not going to work that well.

Once the number passed to the BigDecimal constructor passes the biggest number that can be represented on your system, it will overflow to the constant BigDecimal::INFINITY, which when converted to a string, is just Infinity, and can clearly fit in memory:

BigDecimal('123e+1000000000000000000000000000000000') == BigDecimal::INFINITY
#=> true
Drenmi
  • 8,492
  • 4
  • 42
  • 51
0

Why not convert it to a float? This works for me:

BigDecimal('123e+1000000000000000000').to_f
=> Infinity
miligraf
  • 1,042
  • 9
  • 22
  • @phlegx what do you mean by "should work"? If your computer doesn't have enough memory to allocate for that string then well... maybe good it's not trying – Mike Szyndel Jan 22 '16 at 17:51