However I don’t like this Float behaviour of Ruby. Especially that the
String representation of such values looks correct, while testing for
equality says ‘false’ - like this:
That’s no “ruby” problem. You have to understand what floats are (and
they are that way everywhere, not just ruby): approximations. Think of
it this way: try to represent 1/3 (0.333…) in a decimal precisely.
It doesn’t work. Or try to represent pi in decimal precisely. Doesn’t
work either. The same way a float can never represent some numbers
Also see http://wiki.rubygarden.org/Ruby/page/show/RubyLangFAQ
Maybe do some research of your own on floats, e.g. read a bit about them
I know that this is no Ruby-specific problem and I can live with it in a
more low level language like C, where a ‘float’ is represented by 32/64
bits depending on your processor type, the same as an ‘int’ is stored as
a 32 bit (?) value.
As far as I understand Ruby, a Fixnum is stored as a C ‘int’, but if you
are working with higher/lower numbers (Bignum(s)), Ruby abstracts form
the C ‘int’ data-type to whatever else (possibly just multiple C ‘int’
that are concatenated together).
So my question was, why a similar behaviour couldn’t be done with
floating point values. Here’s my utopia on what I would like to see:
Let’s you have a string representation of a floating point value like
“0.125” (1/8). This value has an EXACT representation as a C ‘float’
value, therefore it is stored like that. If you have “0.295” there is NO
exact representation in a C ‘float’ and therefore the value needs to be
stored otherwise (like BigDecimal does it). The aritmetic calculations
should be chosen accordingly (normal processor instructions on 'float’s
or abstracted from those simple cases where needed).
I didn’t but a lot of thinking in it, so there might be many issues to
solve. But again, it would be nice to have this behaviour in a
programming language that - generally very successfully - follows the
principle of least surprise (POLS).