BigDecimal + Float => Float?

I was just playing around in irb and noticed that while BigDecimal +
Integer
=> BigDecimal, BigDecimal + Float => Float. Is there any reason for
this?
It seems inconsistent and means you have to check the class of any
number you
add to a BigDecimal, which looks very un-Ruby-like to me.

Ashley

I’m guessing that the result didn’t need a BigDecimal so a Float
was good enough. Try the same thing with values that are too large
for Float and the result will likely be typed as a BigDecimal.

-Rob

Rob B. http://agileconsultingllc.com
[email protected]
+1 513-295-4739

On Friday 31 March 2006 15:15, Rob B. wrote:

I’m guessing that the result didn’t need a BigDecimal so a Float
was good enough. Try the same thing with values that are too large
for Float and the result will likely be typed as a BigDecimal.

-Rob

I thought of that- I figured maybe it was an optimisation. But:

irb(main):004:0> (BigDecimal(“1.0000000000000000000000000001”) +
1.0).class
=> Float

So it looks like it always reduces the available precision.

Ashley

I’ve also just realised I meant to post this to ruby-talk :slight_smile:

On Friday 31 March 2006 15:29, Justin F. wrote:

It seems right to me that when you add something imprecise (Float) to
something precise (BigDecimal) the result must be imprecise.

I hadn’t thought about it like that - makes sense now. It depends on
the
context though - a float might represent an exact value, although
arguably
you should store is as a rational if it is.

Ashley

I thought of that- I figured maybe it was an optimisation. But:

irb(main):004:0> (BigDecimal(“1.0000000000000000000000000001”) + 1.0).class
=> Float

So it looks like it always reduces the available precision.

I would write a bug report in the ruby section of www.rubyforge.org for
this.

Best regards,

Karl

Ashley M. wrote:

I was just playing around in irb and noticed that while BigDecimal + Integer
=> BigDecimal, BigDecimal + Float => Float. Is there any reason for this?
It seems inconsistent and means you have to check the class of any number you
add to a BigDecimal, which looks very un-Ruby-like to me.

It seems right to me that when you add something imprecise (Float) to
something precise (BigDecimal) the result must be imprecise.

regards

Justin

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs