-5

What is the best type variable for more precise calculations?

I've used double in BigDecimal and were not accurate.

agentp
  • 6,849
  • 2
  • 19
  • 37
Jose Vieira Neto
  • 131
  • 1
  • 1
  • 8
  • 4
    BigDecimal has arbitrary precision. Define "not accurate". – azurefrog Dec 23 '15 at 18:15
  • Possible duplicate of [Retain precision with double in Java](http://stackoverflow.com/questions/322749/retain-precision-with-double-in-java) – saljuama Dec 23 '15 at 18:48
  • It is a common misconception that you need `BigDecimal` or that i will fix all the problems you have with `double` IMHO using `BigDecimal` just makes find errors harder in many cases as well as being slower. – Peter Lawrey Dec 23 '15 at 18:53

2 Answers2

2

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
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
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