Just Another Victim of the Ambient Morality
6/10/2006 4:55:00 AM
I quoted another post of yours for more context.
"Dave" <djreid@ihug.co.nz> wrote in message
news:1149889807.437723.251690@u72g2000cwu.googlegroups.com...
>
>> 4.1 % 2
> >
>> => 0.0999999999999996
>
> Still got to sort 4.1 % 2 still say it should be .1
Actually, it is 0.1 or, rather, close enough. I'm not intimately
familiar with the implementation of Ruby but my best guess is that Ruby
converted the value 4.1 into the IEEE double floating point representation
and did the relevant operations using that value. The problem is that the
IEEE format cannot accurately represent the value 4.1, representing it as
4.0999999999999996 instead, resulting in the final mod result being as you
see it. This isn't really even a problem specific to the IEEE standard,
considering how Real numbered values simply cannot (hopefully, for obvious
reasons) be accurately represented in finite digital circuitry.
This is exactly why you are always told to never try to directly
compare, with the equals operator, floating point values, in any language.
You will often fail to find equality when you expected it. Instead, you
should specify a delta value to test whether floating point values are
"close enough."
You can see this for yourself if you have access to a C compiler and
debugger. Simply assign the value 4.1 to a variable of type double and then
examine the value of that variable. I think you will be surprised...