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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With