What is the best kind of variable for very accurate calculations?
I have used double and BigDecimal and the rounding is diverging much in the end result.
What is the best kind of variable for very accurate calculations?
I have used double and BigDecimal and the rounding is diverging much in the end result.
No data type will solve your precision problems, whether floating point (% with%), fixed point (% with%) or any other. You need to identify in what sense your calculations are accumulating errors, and try to take steps to circumvent them.
Are you comparing data from very different quantities? (eg, add a very large number and a very small number) If this is the case, the floating point may lose precision, and the way would be to use double
with enough significant numbers to represent the full range of numbers with which you are dealing with.
Are you doing a very long sequence of calculations, using the minimum representation required for the numbers you are dealing with? If this is the case, the small rounding errors in each individual calculation wind up accumulating, making a big difference at the end. Some possible solutions would be:
Increase the number of significant digits. If your entries are numbers with 5 decimal places, for example, increase them to 10. There is no rule for this, just look at how long your calculation sequence is and determine which is the biggest error that can be propagated at the end of that sequence .
(an example solution via more digits: in this answer I needed to calculate PI through a series. the exact number of digits brought the wrong result because the individual contributions of the terms of the series were truncated.It was necessary to add more digits to the numbers during the calculation, although in the end result these digits were discarded)
Use intervals instead of simple numbers. This technique (which, if I remember correctly, was proposed by Knuth) consists in taking the result of an operation taking into account both its ceiling and its floor (in relation to the desired precision), and when applying the next operation, floor-to-floor, floor-ceiling and ceiling-floor, using the maximum and minimum found as the new range. Repeat for each operation, and at the end average the resulting interval (and still break you have a margin of error).