Automatically moving to BigDecimal when float is out of range

258 views Asked by At

Huge Float numbers are not automatically converted to BigDecimal as with conversion from Fixnum to Bignum. For instance, 2.5**1000 generates Infinity. I can manually define a BigDecimal as BigDecimal('2.5')**1000, but this will slow down the computation when the numbers are not huge and BigDecimal is not required.

Is there any way to make the transition from Float to BigDecimal automatic (similar to the transition from Fixnum to Bignum)? Or is there any other Ruby class which does this? I don't care about the precision of the floating point numbers.

1

There are 1 answers

5
Aleksei Matiushkin On

As one possibility I see to monkeypatch the Float class. Since the overflow is likely to appear on arithmetic operations only, you probably need to overwrite five methods :+,:-, :/, :*, :** like that:

require 'bigdecimal'
class Float
  alias_method :__power, :** 
  def ** other
    result = self.__power other
    result.abs == Float::INFINITY ? BigDecimal(self, 0) ** other : result 
  end
end
puts 2.5 ** 1000
#⇒ 0.87.....E398

Not very elegant, but it does a trick.