Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double subtraction precision issue

Tags:

java

double

My coworker did this experiment:

public class DoubleDemo {        public static void main(String[] args) {            double a = 1.435;            double b = 1.43;            double c = a - b;            System.out.println(c);       }  } 

For this first-grade operation I expected this output:

0.005 

But unexpectedly the output was:

0.0050000000000001155 

Why does double fails in such a simple operation? And if double is not the datatype for this work, what should I use?

like image 389
Carlos Gavidia-Calderon Avatar asked Mar 28 '12 15:03

Carlos Gavidia-Calderon


People also ask

Why is double not accurate?

doubles are not exact. It is because there are infinite possible real numbers and only finite number of bits to represent these numbers.

How do you subtract two long variables in Java?

Syntax : public static long subtractExact(long x, long y) Parameter : x : the first value y : the second value to be subtracted from the first Return : This method returns the difference of the arguments. Exception : It throws ArithmeticException - if the result overflows a long. Example :To show working of java.

What is double precision floating-point in Java?

Double-precision floating-point format (sometimes called FP64 or float64) is a computer number format, usually occupying 64 bits in computer memory; it represents a wide dynamic range of numeric values by using a floating radix point.


2 Answers

double is internally stored as a fraction in binary -- like 1/4 + 1/8 + 1/16 + ...

The value 0.005 -- or the value 1.435 -- cannot be stored as an exact fraction in binary, so double cannot store the exact value 0.005, and the subtracted value isn't quite exact.

If you care about precise decimal arithmetic, use BigDecimal.

You may also find this article useful reading.

like image 158
Louis Wasserman Avatar answered Oct 14 '22 16:10

Louis Wasserman


double and float are not exactly real numbers.

There are infinite number of real numbers in any range, but only finite number of bits to represent them! for this reason, rounding errors is expected for double and floats.

The number you get is the closest number possible that can be represented by double in floating point representation.

For more details, you might want to read this article [warning: might be high-level].

You might want to use BigDecimal to get exactly a decimal number [but you will again encounter rounding errors when you try to get 1/3].

like image 43
amit Avatar answered Oct 14 '22 16:10

amit