A
A
Artyom2014-10-24 16:47:28
Java
Artyom, 2014-10-24 16:47:28

Exact calculations in java?

There was a question with computational mathematics. I do some tasks where it is necessary to calculate the roots of equations with an accuracy of 6 decimal places. I do everything according to algorithms. In this regard, the question arose whether the built-in types are suitable for calculations of this type (only 6 decimal places). I tried to use BigDecimal, the result is the same, the answers are correct only up to 3-4 digits. I do according to typical examples.
In this regard, the error may be in the calculations (because there are already ready-made formulas for calculations in the typical example and the result of their calculations differs from the results in the book). In this regard, the question is how to count in Java? And if everything is considered correct and the calculations are correct, then why is the answer only partially correct? Is it about rounding intermediate calculations to 6 decimal places? Then without rounding should also be the correct answer, right?
The method is not that complicated.
I solved two examples, everywhere the answer is not completely correct.
Specifically interested in "Solving systems of nonlinear equations by steepest descent"

rs1 = 2*(Math.cos(1.5 + x1)*(Math.sin(x1 + 1.5) + 2.9 - x2) + x1 + Math.cos(x2-2));	
rs2 = -2 * (Math.cos(x2 - 2) * Math.sin(x2 - 2) - x2 + Math.sin(x1 + 1.5) + 2.9 + x1*Math.sin(x1 + 1.5));

An example of calculating the value of the first and second derivatives.
We just recalculate them every time, substituting the previous x values ​​until the difference between them and the current ones is less than 0.000001, but the answer is correct only up to 3 ~ decimal places

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
SilentFl, 2014-10-27
@Artem_007

Try changing the order of calculations.
Example one, a feature of representing fractional numbers in memory: 1/10+1/10 in floats != 2/10 (because 1/10 is represented in memory as 0.09999(9)) - this can be bypassed by casting to a common denominator ( 1+1)/10.
An example of the second, a feature of processor calculations: the sum of the series 1/10+1/100+1/1000 will be less accurate than the sum of 1/1000+1/100+1/10. such a difference is due to the fact that two operands must be reduced to the same order of the mantissa, and in most processors the second operand is subjected to this, with the rejection of "non-fitting" bits, and, accordingly, a decrease in the accuracy of calculations.

D
Dmitry, 2014-10-24
@CTAKAH4uK

www.apfloat.org/apfloat_java

M
MilkyWay, 2014-10-24
@MilkyWay

BigDecimal can't just be multiplied with operand "*"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question