Float/Double Substraction Bug ?

  • Thread starter Thread starter cybertof
  • Start date Start date
C

cybertof

Hello,

I have the strange beeing :

float f1 = 108.88F;
float f2 = 111.11F;
float f3 = f1 - f2;
double d1 = 108.88;
double d2 = 111.11;
double d3 = d1 - d2;

f3 contains -2.23000336
d3 contains -2.230000000000004

instead of -2.23.


Am i missing something ?


Regards,
Cybertof.
 
Hi cybertor,

This is normal behavious of binary based floating point variables.
They are only rounded to the value you want.
You might try using decimal variables instead.
 
Hi Miha !

How do you explain ?
Does it mean that with single & double, you always get calculation
errors ?

When can you use binary based floating point variables if you cannot
make correct calculations with them ?


Regards,
Cybertof.
 
cybertof said:
How do you explain ?
Does it mean that with single & double, you always get calculation
errors ?

Often, yes - but not always.
When can you use binary based floating point variables if you cannot
make correct calculations with them ?

In fact, the calculations may well be performing without any error, but
with the initial values not being what you think they were.

See http://www.pobox.com/~skeet/csharp/floatingpoint.html for more
information.
 
Back
Top