[rspec-users] Why can not a BigDecimal be compared to a Float via "==". How should I handle this???

Rick DeNatale rick.denatale at gmail.com
Sun Jan 11 13:53:05 EST 2009


On Sun, Jan 11, 2009 at 9:21 AM, David Chelimsky <dchelimsky at gmail.com>wrote:

> On Sun, Jan 11, 2009 at 4:05 AM, Greg Hauptmann
> <greg.hauptmann.ruby at gmail.com> wrote:
> > I've gone with the following
> >      ai.amount.should == BigDecimal('-323.03')
> > However I'm still a bit surprised that Ruby itself does allow a good "=="
> > test between a Float and a BigDecimal.  Perhaps there's a reason that I'm
> > missing?
>
> Very telling is this:
>
> >> require 'bigdecimal'
> => true
> >> BigDecimal.new(3333333.0) == 3333333.0
> TypeError: can't convert Float into String
>        from (irb):4:in `new'
>        from (irb):4
>
> As for why, I think you'll get some good insights if you post the
> ruby-lang mailing list, but I can take shot.
>
> BigDecimal has explicit precision. Float does not. Imagine the
> developer at the bank explaining that the thousands of dollars
> discrepancy last year was due to an average miscalculation of 0.00005
> per transaction because sometimes the code used BigDecimal, and
> sometimes it used Float.
>

Even more telling is this:
irb(main):001:0> 1.0 / 3.0
=> 0.333333333333333
irb(main):002:0> (1.0 / 3.00) ==  0.333333333333333
=> false

This has little to do with rspec or Ruby, and everything to do with floats.

Floats are approximations, it's a mistake to thing of them as equivalent to
the mathematical concept of real numbers, or even rational numbers. There
are several issues here including

1. Floats are not infinite precision, they have a fixed number of bits or
digits, this means that in-between any two consecutive real number which CAN
be represented by a float, there are an infinite number of reals which
cannot.

2. As is the case in decimal fractions, where some rational numbers such as
1/3 cannot be represented without an infinite number of decimal digits,
there are similar values dependent on the base used for the float
representation.

There's a whole branch of computer science, Numerical Analysis, comprised in
large part of understanding how Floats differ from the mathematical ideal.


-- 
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20090111/2c6c29ee/attachment-0001.html>


More information about the rspec-users mailing list