How to ensure computational accuracy in BigDecimal

Asked 2 years ago, Updated 2 years ago, 33 views

We create a program that parses user-defined formulas (only rational four-way operations) and computes them using BigDecimal.
There is a requirement specification that says, "Calculation results ensure that up to two decimal places match manual results."
To be exact, it matches "Manually rounded to three decimal places."

The divide method of BigDecimal has a scale designation, but what value should I specify for scale in each division to guarantee the above results?
Or is it fundamentally impossible to guarantee?

Even though I can't come to a conclusion, I'll mention what I thought.

  • Round 3 decimal places at the end of the operation, so you must eventually maintain the correct state to the 3rd digit
  • Even if scale=3 is specified for
  • divide, 3000 times 1/3=0.333 results in 999.There is no guarantee of decimal places.
    • (1/3)*3000 must be replaced with 3000*1/3 to be fundamentally guaranteed?
    • Or "Keep sufficiently large scale" policy?
    • If <li>for example,<code>scale=6>/code>,<code>1/3=0.333333>/code>, this becomes<code>999.999> in 3000 times.Rounding off the third decimal place is 1000.
    • What is a "big enough scale"? Can you define a specific value?
  • (1/3)*3000 must be replaced with 3000*1/3 to be fundamentally guaranteed?
  • Or "Keep sufficiently large scale" policy?
  • If <li>for example,<code>scale=6>/code>,<code>1/3=0.333333>/code>, this becomes<code>999.999> in 3000 times.Rounding off the third decimal place is 1000.
  • What is a "big enough scale"? Can you define a specific value?

[Additional note]

  • Is it possible to realize the limited specification that "this kind of formula can guarantee accuracy"?
    • (a+b)/(x*y) should be "one high division" and "the last form of division"?
  • (a+b)/(x*y) should be "one high division" and "the last form of division"?

java

2022-09-30 19:16

1 Answers

I can't answer the question, but can I meet the requirement specification by using org.apache.commons.math4.fraction.Fraction that handles fractions?

Since there is division, I think it would be better to separate the numerator and denominator (for example, using a class with numerator and denominator internally like Fraction).

Even if you specify a sufficiently large scale, you must change the order of the calculations

System.out.println(new BigDecimal(1).divide(new BigDecimal(3), MathContext.DECIMAL128).multiple(new BigDecimal(3));

However, there is a situation where 0.9999999999999999999999999999999.


2022-09-30 19:16

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.