Floating-point arithmetic is inexact. When you add up n
identical double
s, and divide the result by n
, you don't always get the number you started with.
For example, the following:
double x = 0.1;
double y = x + x + x;
System.out.println(y / 3. - x);
prints
1.3877787807814457E-17
I highly recommend What Every Computer Scientist Should Know About Floating-Point Arithmetic.