Todd Benson
7/17/2007 1:17:00 AM
On 7/16/07, Robert Brown <rob99brown@yahoo.com> wrote:
> Hi all,
>
> I'm doing some complex math which I need to be based on BigDecimal
> accuracy (not Float). It seems that ruby defaults to Float when there's
> a mixture of type in there, e.g.
>
> Code :
>
> 1. irb(main):001:0> require 'bigdecimal'
> 2. => true
> 3. irb(main):002:0> a = 5.123
> 4. => 5.123
> 5. irb(main):003:0> b = BigDecimal("6.789")
> 6. => #<BigDecimal:8b4c0,'0.6789E1',8(8)>
> 7. irb(main):004:0> c = a * b
> 8. => 34.780047
> 9. irb(main):005:0> c.class
> 10. => Float
>
> Is there a way I can force a BigDecimal outcome.
>
> One way I guess would work is to make sure all args in the calculation
> are BigDecimal, but that's a bit tiresome. For a start, I'd have to
> type check each arg and convert to BigDecimal if it was not BigDecimal -
> that's gotta be slow...
>
> On a related note, how do I initalize a BigDecimal from a Float (without
> converting to string first). How could I extend BigDecimal for this?
>
>
> Thanks,
>
>
>
> Rob
Here's a quick fix. There may be a better way to handle this, though.
Again, I'll give the usual warning about modifying core classes: you
shouldn't normally do it unless you can be certain it won't break
yours or anyone else's code.
class Float
require 'bigdecimal'
def big
BigDecimal self.to_s
end
end
p pi = Math::PI.big
# prints out something like
# #<BigDecimal:2df3ffc,'0.3141592653 58979E1',20(20))
p "\n"
p pi * 2.0.big
# prints out something like
# #<BigDecimal:2deb35c,'0.6283185307 17958E1',20(36))
p "\n"
Todd