Floating-point values are finite in size and therefore can only represent real values with finite precision. This leads to rounding errors when you need higher precision than they can store.
In particular, when adding a small number (for example, summing) to a much larger number (for example, your battery), the accuracy loss can be quite large compared to a small number, which gives a significant error; and errors will vary by order.
Typically, a float
has 24 bits of precision, which corresponds to about 7 decimal places. Your battery needs 10 decimal places (about 30 bits), so you will lose this accuracy. As a rule, double
has 53 bits (about 16 decimal places), so your result can be represented exactly.
A 64-bit integer might be the best option here, since all inputs are integers. Using the whole avoids the loss of accuracy, but poses a danger of overflow if the inputs are too large or too large.
To minimize error, if you cannot use a sufficiently large drive, you can sort the input so that the smallest values are accumulated first; or you can use more sophisticated methods, such as summing Kahan .
source share