Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How two recursive numbers stored as doubles sum up to an integer

Tags:

java

int

double

This is just out of curiosity. If I store two recursive numbers or irrational numbers in two doubles and then perform some operations, how does it produce actual result?

For example,

double d1=7d/3;
double d2=5d/3;
double sum=d1+d2;
System.out.println(new BigDecimal(sum)); //prints exactly 4

Another one:

double d1=log10(3);
double value=Math.pow(10,d1);
System.out.println(new BigDecimal(value)); //prints exactly 3

How these accurate results are generated?

like image 589
Victor Mukherjee Avatar asked Oct 20 '12 06:10

Victor Mukherjee


1 Answers

If you amend your code slightly you will see that d1 and d2 are not exactly 7/3 or 5/3. The reason why d1+d2 is exactly 4 is that 4 can be represented exactly as a double and is the closest to the exact result of this addition.

public static void main(String[] args) throws Exception {
    double d1 = 7d / 3;
    double d2 = 5d / 3;
    System.out.println(new BigDecimal(d1)); //2.333333333333333481363069950020872056484222412109375
    System.out.println(new BigDecimal(d2)); //1.6666666666666667406815349750104360282421112060546875
    System.out.println(new BigDecimal(d1).add(new BigDecimal(d2))); //4.0000000000000002220446049250313080847263336181640625
    double sum = d1 + d2; 
    System.out.println(new BigDecimal(sum)); //4
}

Java follows the IEEE 754 convention:

the sum is rounded to the nearest value in the chosen value set using IEEE 754 round-to-nearest mode

like image 92
assylias Avatar answered Sep 25 '22 19:09

assylias