Turbo_Thorsten wrote ...

2022/5/11

## Problem with adding double to double

Turbo_Thorsten

2022/5/11

I have a problem with adding double to double. The program sometimes adds like 0,2000000004 to the counter instead of 0,2. Why is that so?
danpost

2022/5/11

Turbo_Thorsten wrote...
I have a problem with adding double to double. The program sometimes adds like 0,2000000004 to the counter instead of 0,2. Why is that so?
As computers store data in bits, each as a one or a zero, any partial units must be rounded to some fractional value. You are adding the value of 1/5 (0.2), which in binary is 0.0011001100110011001100... The computer cannot store this value exactly. You can, instead of adding double values, add int values, specifically, 1 or 2, in your case. Then divide by 5 or 10 using double values when needed. This will eliminate any accumulation of error.
Spock47

2022/5/11

In the computer, numbers are stored in binary (only 0s and 1s as ciphers) instead of decimal (0, 1, 2, ...9). That means, for floating point numbers, the fraction ciphers, will be powers of (1/2): 0.1 (binary) is 1/2 0.01 (binary) is 1/4 0.001 (binary) is 1/8 and so on... Now, it can only add up these ciphers to represent numbers, so, e.g. 3/4 can be easily stored in binary since it is 1/2 + 1/4, so it's binary representation is 0.11 (binary) = 0.75 (decimal). But the binary representation of 0.2 (decimal) is very difficult because it can not be represented by a finite number of 1/2^n fractions. But a double only has a finite number of bits (It is 64 bits in Java), therefore the value saved in the double will only be an approximation of 0.2 (decimal) and not actually exactly 0.2, e.g. the stored value will be more like 0.200000000000000011102230246251565404236316680908203125... In most cases, the difference between the actual value and the stored value will not be visible. But when modifying the value (e.g. with addition and especially multiplication), the difference can get bigger and then become visible like in your case. So, whether the accuracy of Double is good enough, depends strongly on what operations one is doing with the numbers. Also, doing operations in the "right" order can help with keeping the difference small. In Java, there is a type called BigDecimal that can be used, if bigger or absolute precision/accuracy is needed (e.g. for any financial values): https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html Edit: Danpost was faster than me. :) Live long and prosper, Spock47
Turbo_Thorsten

2022/5/12

Thank yall for the answers. I got an easy solution but the explanation is very helpful :)