diff options
| author | Sven Eisenhauer <sven@sven-eisenhauer.net> | 2023-11-10 15:11:48 +0100 |
|---|---|---|
| committer | Sven Eisenhauer <sven@sven-eisenhauer.net> | 2023-11-10 15:11:48 +0100 |
| commit | 33613a85afc4b1481367fbe92a17ee59c240250b (patch) | |
| tree | 670b842326116b376b505ec2263878912fca97e2 /Master/Reference Architectures and Patterns/hjp5/examples/Listing1706.java | |
| download | Studium-master.tar.gz Studium-master.tar.bz2 | |
Diffstat (limited to 'Master/Reference Architectures and Patterns/hjp5/examples/Listing1706.java')
| -rw-r--r-- | Master/Reference Architectures and Patterns/hjp5/examples/Listing1706.java | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/Master/Reference Architectures and Patterns/hjp5/examples/Listing1706.java b/Master/Reference Architectures and Patterns/hjp5/examples/Listing1706.java new file mode 100644 index 0000000..4f1c41d --- /dev/null +++ b/Master/Reference Architectures and Patterns/hjp5/examples/Listing1706.java @@ -0,0 +1,43 @@ +/* Listing1706.java */
+
+import java.math.*;
+
+public class Listing1706
+{
+ public static final BigDecimal ZERO = new BigDecimal("0");
+ public static final BigDecimal ONE = new BigDecimal("1");
+ public static final BigDecimal TWO = new BigDecimal("2");
+
+ public static BigDecimal sqrt(BigDecimal x, int digits)
+ {
+ BigDecimal zero = ZERO.setScale(digits + 10);
+ BigDecimal one = ONE.setScale(digits + 10);
+ BigDecimal two = TWO.setScale(digits + 10);
+ BigDecimal maxerr = one.movePointLeft(digits);
+ BigDecimal lower = zero;
+ BigDecimal upper = x.compareTo(one) <= 0 ? one : x;
+ BigDecimal mid;
+ while (true) {
+ mid = lower.add(upper).divide(two, BigDecimal.ROUND_HALF_UP);
+ BigDecimal sqr = mid.multiply(mid);
+ BigDecimal error = x.subtract(sqr).abs();
+ if (error.compareTo(maxerr) <= 0) {
+ break;
+ }
+ if (sqr.compareTo(x) < 0) {
+ lower = mid;
+ } else {
+ upper = mid;
+ }
+ }
+ return mid;
+ }
+
+ public static void main(String[] args)
+ {
+ BigDecimal sqrtTwo = sqrt(TWO, 100);
+ BigDecimal apxTwo = sqrtTwo.multiply(sqrtTwo);
+ System.out.println("sqrt(2): " + sqrtTwo.toString());
+ System.out.println("check : " + apxTwo.toString());
+ }
+}
\ No newline at end of file |
