Page 1 of 1

PostPosted: Tue Feb 07, 2006 10:57 am
by Emanuelll
Could anyone please hel me:(

In my sourcecode there are:

<i>#define SOFT_PREIS 1.80</i>

after that I increase float variable:

<i>float total = 0.00;
total = total + SOFT_PREIS;</i>

let me show you the value of total:

after the first increase:
after the second:
after the third:
the fourth:

Isn't it crazy?

Thank You

PostPosted: Tue Feb 07, 2006 1:33 pm
by mgreen
This behavior is actually normal. Floating point numbers have only a limited precision. Typically, "single" precision numbers have somewhere between 7-8 decimal digits of precision and "double" precision numbers approximately double that. Usually they are binary floating point with the exponent in bits rather than decimal digits. As a result, numbers that appear to be represented exactly like "1.80" are actually represented in binary with very small errors in the least significant binary digits. When you repeatedly add them, the error accumulates as you have seen. The solution is to use double precision sometimes, to round the result to a smaller number of decimal places when displaying it, or to do the calculation as integer fixed point and to simply display the result with a decimal point inserted. This is often done for currency amounts. You would use "#define SOFT_PREIS 180", declare all currency values as integer, and write a display function that takes an integer value, converts it to a string like "180" and inserts a decimal point to make "1.80". You have to account for numbers smaller than 100 like ".99" or ".09". Some languages (and computers) did all their floating point calculations in decimal representing each digit in 4 bits with the exponent as a decimal exponent, but this is slower than doing it all in binary and the amount of precision in a specific amount of storage is less (64 bits would provide maybe 13 digits rather than 16).

PostPosted: Tue Feb 07, 2006 6:17 pm
by Emanuelll
@ mgreen

Thanx, for the response. It makes me a bit sad and I cannot understand why there are float Varables.

Thanx again.


PostPosted: Wed Feb 08, 2006 2:39 am
by mgreen
For many scientific and engineering calculations, standard floating point works very well. There is a very well developed area of mathematics that deals with calculations with limited precision and can be used to estimate the overall error for calculations of this sort or to determine the precision (number of bits) needed to make a calculation with a specified accuracy.

It is really very easy to write a program involving financial calculations using fixed point (or integer). For US dollar amounts, the amounts are calculated in cents. The calculations are essentially the same with Euros or Pounds.