Lucifer Lawliet
Lucifer Lawliet

Reputation: 31

If the result of a double is divisible by another double is accurate?

I know the float and double is not accurate.I have a question like this.

double a=4.0/2.0;
System.out.println(a);

The output is 2.0. So whether the result is accurate or not. The question comes from when I read the book Java Programming Language. It shows me a method to set the scale of output like this.

System.out.println((int)(area*100)/100.0);

The statement set the output to two decimal places.And I know the floating-point arithmetic is not accurate.So can the statement always work?

Upvotes: 0

Views: 632

Answers (1)

Patricia Shanahan
Patricia Shanahan

Reputation: 26175

In the first case, the result will be exactly 2.0. The reason is that 4.0 and 2.0 are both exactly representable as Java doubles. The divide operator returns the closest double to the real number division result, which is 2.0.

In the second case, whether you get an exact result or not will depend on the value of area. All exactly representable two decimal place doubles end in .00, .25, .50, or .75. The remaining two decimal place doubles can only be approximated.

The cast to int causes inaccuracies, and should be replaced by Math.round. The problem is that a positive double very slightly less than an integer casts to the next integer down, but rounds to the closest integer. Here is a program illustrating this issue:

import java.math.BigDecimal;

public class Test {
  public static void main(String[] args) {
    double area = 0.29;
    System.out.println(new BigDecimal(area));
    System.out.println(new BigDecimal(area*100));
    System.out.println(new BigDecimal((int)(area*100)/100.0));
    System.out.println((int)(area*100)/100.0);
    System.out.println(Math.round(area*100)/100.0);
  }
}

Output:

0.289999999999999980015985556747182272374629974365234375
28.999999999999996447286321199499070644378662109375
0.2800000000000000266453525910037569701671600341796875
0.28
0.29

The closest double to 0.29 is slightly smaller than it, and the result of multiplying by 100 is also very slightly less than 29. Casting to int gets 28, but rounding gets 29.

Upvotes: 1

Related Questions