简体   繁体   English

NoMemoryError:无法使用BigDecimal .to_s方法分配内存

[英]NoMemoryError: failed to allocate memory using BigDecimal .to_s method

I use Ruby 2.2.3 and Rails 4.2.3 . 我使用Ruby 2.2.3Rails 4.2.3 I get an NoMemoryError: failed to allocate memory using the following code in irb console: 我收到一个NoMemoryError: failed to allocate memoryirb控制台中使用以下代码NoMemoryError: failed to allocate memory

# 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 这是BigDecimal的代码: https : //github.com/rails/rails/blob/v4.2.3/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb

The fact that you run out of memory is nothing strange. 内存不足的事实并不奇怪。 The number 123e+1000000000000000000 has a quintillion zeroes. 数字123e+1000000000000000000具有一个五亿个零。 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. 每字符一个字节,您正在(大约)查看10^18字节, 10^15 KB, 10^12兆字节或10^9千兆字节。 So unless you have in the range of a billion gigabytes of RAM, it's not going to work that well. 因此,除非您拥有十亿千兆字节的RAM,否则它将无法正常工作。

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构造函数的数字超过了系统上可以表示的最大数字,它将溢出到常数BigDecimal::INFINITY ,将其转换为字符串后,它就是Infinity ,并且可以明显地容纳在内存中:

BigDecimal('123e+1000000000000000000000000000000000') == BigDecimal::INFINITY
#=> true

Why not convert it to a float? 为什么不将其转换为浮点数? This works for me: 这对我有用:

BigDecimal('123e+1000000000000000000').to_f
=> Infinity

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM