Question

While running kmeans clustering in java the absolute difference between the data points 0.33 and 0.99 is displayed as 0.659999999 instead of 0.66.

Why is that?

Both the variables holding the data are of type double and I am using the Math.abs() function.

I saw such a problem only for 0.99. When subtracting using other values, the results were fine.

Thanks for any help

Was it helpful?

Solution

Floating-point datatype (float and double) can't be accurately represented in memory bits. They are approximately represented in memory.

Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation. Although there are infinitely many integers, in most programs the result of integer computations can be stored in 32 bits. In contrast, given any fixed number of bits, most calculations with real numbers will produce quantities that cannot be exactly represented using that many bits. Therefore the result of a floating-point calculation must often be rounded in order to fit back into its finite representation. This rounding error is the characteristic feature of floating-point computation

What Every Computer Scientist Should Know About Floating-Point Arithmetic

OTHER TIPS

This is how floating point numbers behave. They are not accurate.

Check this:- What Every Computer Scientist Should Know About Floating-Point Arithmetic

Also to add Floating point numbers use binary fractions and not decimal fractions. And if you need exact decimal values, you should use java.math.BigDecimal

You may check this answer as well for more reasoning and details:

Floating point rounding errors. 0.1 cannot be represented as accurately in base-2 as in base-10 due to the missing prime factor of 5.

Doubles are not exact due to the way they are stored in memory. More information here: https://en.wikipedia.org/wiki/Double-precision_floating-point_format

If you need an exact result, you should look into BigDecimal

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top