Possible Duplicate:
Dealing with accuracy problems in floating-point numbers
I was quite surprised why I tried to multiply a float in C (with GCC 3.2) and that it did not do as I expected.. As a sample:
int main() {
float nb = 3.11f;
nb *= 10;
printf("%f\n", nb);
}
Displays: 31.099998
I am curious regarding the way floats are implemented and why it produces this unexpected behavior?
First off, you can multiply floats. The problem you have is not the multiplication itself, but the original number you’ve used. Multiplication can lose some precision, but here the original number you’ve multiplied started with lost precision.
This is actually an expected behavior.
floats are implemented using binary representation which means they can’t accurately represent decimal values.See MSDN for more information.
You can also see in the description of float that it has 6-7 significant digits accuracy. In your example if you round
31.099998to 7 significant digits you will get31.1so it still works as expected here.doubletype would of course be more accurate, but still has rounding error due to it’s binary representation while the number you wrote is decimal.If you want complete accuracy for decimal numbers, you should use a decimal type. This type exists in languages like C#. http://msdn.microsoft.com/en-us/library/system.decimal.aspx
You can also use rational numbers representation. Using two integers which will give you complete accuracy as long as you can represent the number as a division of two integers.