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?
If you amend your code slightly you will see that
d1andd2are not exactly7/3or5/3. The reason whyd1+d2is exactly4is that4can be represented exactly as a double and is the closest to the exact result of this addition.Java follows the IEEE 754 convention: