big double division

• 10-11-2009, 07:50 PM
grilo
big double division
The output of the following program is 0.8402000002094746 and it should be 0.8402.

Anyone knows why? Is there any way to solve the problem?

public class Main {

public static void main(String[] args){

double p = 0;
double l = 10000000;
double x = 0.8402;

for(int i = 0; i < l; i++){
p += x;
}

System.out.println(p / l);
}
}
• 10-11-2009, 08:24 PM
Fubarable
You're running into a general issue of how digital computers handle floating point numbers. I don't have any links handy, but you might want to google this topic to learn more about it as it is not a Java issue per se, but instead is a general digital computing issue (for instance, how do you precisely represent 3/7 in only binary? Think about this).

There are two issues here, one is one of numeric accuracy, and the other regarding display of the number. The result that the program is outputting is accurate to at least 9 significant digits, and so it is reasonably accurate. To display it better, you may wish to look into formatting the String that displays the number either via NumberFormat (for example DeicmalFormat) or String.format (printf is one of its variants).
• 10-11-2009, 08:29 PM
Fubarable
For instance, here are two ways of displaying a prettier output:
Code:

```import java.text.DecimalFormat; public class Main {   public static void main(String[] args) {     double sum = 0;     double bigNumber = 10000000;     double littleNumber = 0.8402;     for (int i = 0; i < bigNumber; i++) {       sum += littleNumber;     }     DecimalFormat df = new DecimalFormat("0.####");     System.out.println(df.format(sum / bigNumber));     System.out.printf("%6.4f %n", sum/bigNumber);   } }```
Also, sorry to be blunt, but your variable naming is poor at best since the variable names aren't self-describing in that they don't describe what the values represent, and dangerous at worst, since it is very easy to confuse the letter "l" with the number 1. Finally, please use code tags when posting here.

Oh, and welcome!
• 10-11-2009, 09:37 PM
grilo
Thanks
Thanks for the answer. I was concerned with accuracy since after many many such operations we can have a deviation that in some situations (critical systems, scientific calculations) may have some meaning.

I'm sorry about the tags and the variable naming.

Grilo
• 10-11-2009, 10:07 PM
Fubarable
For critical floating point numbers such as currency, you should not use double but instead use BigDecimal. While it gives a significant performance hit, sometimes accuracy trumps speed.