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.
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?1000
.(1/3)*3000
must be replaced with 3000*1/3
to be fundamentally guaranteed?1000
.
[Additional note]
(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"?
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
.
© 2024 OneMinuteCode. All rights reserved.