Reputation: 182
ApFloat http://www.apfloat.org/ is a C/C++/Java math library that can calculate many trascendental operations such as square roots, exponentiations, logarithms, trigonometric/hyperbolic functions, numeric value of π, etc. with numbers of arbitrary precision, which are not available in the BigDecimal
Java class.
We all know that the expansion of 4/3 is infinite: 1.333.... so when we try to get it at any specific precision, no matters how long it is, there will be loss of information, but the rounding mode is important, too, i.e.
Unfortunately, the rounding mode cannot be specified when performing such those operations, maybe because "Due to different types of round-off errors that can occur in the implementation, no guarantees about e.g. monotonicity are given for any of the methods."
There is, however a method to round an ApFloat numbers with a specific precision and rounding mode http://www.apfloat.org/apfloat_java/docs/org/apfloat/ApfloatMath.html#round-org.apfloat.Apfloat-long-java.math.RoundingMode-
A simple solution could be calculating the operation with an extra precision and then rounding the result with the original precision and desired rounding mode, as the following example:
// Trying to get the square root of 2
// with precision of 10
// and different roundig modes
Apfloat two = new Apfloat(2, 15); // precision is 15, not 10
// result: 2
Apfloat sqrt = ApfloatMath.sqrt(two);
// result: 1.41421356237309
ApfloatMath.round(sqrt, 10, RoundingMode.FLOOR);
// result: 1.414213562
ApfloatMath.round(sqrt, 10, RoundingMode.CEILING);
// result: 1.414213563
The questions are:
Upvotes: 0
Views: 404
Reputation: 135
Here you go, I hope it helps
public static void main(String[] args) {
Apfloat two = new Apfloat(2, 15); // Line 1: If you want precision be 10, than you can´t get result 1.41421356237309 on Line 4, because result have more than 10 numbers after . (decimal dot)
// you can add new Apfloat variable with precision 15 for line 4 and for line 5,6 with precision 10
System.out.print("Line2: Expected: 2 Result:" + two + "\n"); // Line 2:
Apfloat sqrt = ApfloatMath.sqrt(two); // Line 3:
System.out.print("Line4: Expected: 1.41421356237309 Result:" + sqrt + "\n"); // Line 4:
System.out.print("Line5: Expected: 1.414213562 Result:" + ApfloatMath.round(sqrt, 10, RoundingMode.FLOOR) + "\n"); // Line 5:
System.out.print("Line6: Expected: 1.414213563 Result:" + ApfloatMath.round(sqrt, 10, RoundingMode.CEILING) + "\n"); // Line 6:
}
Result:
Upvotes: 0