What is the best type variable for more precise calculations?
I've used double in BigDecimal and were not accurate.
What is the best type variable for more precise calculations?
I've used double in BigDecimal and were not accurate.
A common mistake is calling
double d = ....
BigDecimal bd = new BigDecimal(d);
e.g.
BigDecimal bd = new BigDecimal(0.1);
System.out.println(bd);
prints
0.1000000000000000055511151231257827021181583404541015625
This produces a precise representation of the double which is often not what was intended. Instead you should use
double d = ....
BigDecimal bd = BigDecimal.valueOf(d);
As this produces the BigDecimal for the shortest decimal value which would be this double
BigDecimal bd = BigDecimal.valueOf(0.1);
System.out.println(bd);
prints
0.1
if by accurate, you mean precision:
the precision can not be infinite (or you should use another symbolical representation).
When you use some functions:
1 you have to define precision (which can be very big).
2 you have to take in consideration rounding mode also.
And in many cases, math libraries can not predict precision result, if you reuse values for further calculations. So you have to track the precision.
Example with 1/3, and 100 decimals:
// 1/3
BigDecimal one=new BigDecimal(1);
BigDecimal three=new BigDecimal(3);
BigDecimal one_third=one.divide(three,100,RoundingMode.HALF_DOWN); // third parameter is round mode
System.out.println("1/3="+one_third);
gives:
1/3=0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333