1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 /* 18 * The above license covers additions and changes by AOSP authors. 19 * The original code is licensed as follows: 20 */ 21 22 // 23 // Copyright (c) 1999, Silicon Graphics, Inc. -- ALL RIGHTS RESERVED 24 // 25 // Permission is granted free of charge to copy, modify, use and distribute 26 // this software provided you include the entirety of this notice in all 27 // copies made. 28 // 29 // THIS SOFTWARE IS PROVIDED ON AN AS IS BASIS, WITHOUT WARRANTY OF ANY 30 // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, 31 // WARRANTIES THAT THE SUBJECT SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT 32 // FOR A PARTICULAR PURPOSE OR NON-INFRINGING. SGI ASSUMES NO RISK AS TO THE 33 // QUALITY AND PERFORMANCE OF THE SOFTWARE. SHOULD THE SOFTWARE PROVE 34 // DEFECTIVE IN ANY RESPECT, SGI ASSUMES NO COST OR LIABILITY FOR ANY 35 // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES 36 // AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY SUBJECT SOFTWARE IS 37 // AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. 38 // 39 // UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING, 40 // WITHOUT LIMITATION, NEGLIGENCE OR STRICT LIABILITY), CONTRACT, OR 41 // OTHERWISE, SHALL SGI BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, 42 // INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER WITH RESPECT TO THE 43 // SOFTWARE INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK 44 // STOPPAGE, LOSS OF DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL 45 // OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SGI SHALL HAVE BEEN INFORMED OF 46 // THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT 47 // APPLY TO LIABILITY RESULTING FROM SGI's NEGLIGENCE TO THE EXTENT APPLICABLE 48 // LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE 49 // EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THAT 50 // EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. 51 // 52 // These license terms shall be governed by and construed in accordance with 53 // the laws of the United States and the State of California as applied to 54 // agreements entered into and to be performed entirely within California 55 // between California residents. Any litigation relating to these license 56 // terms shall be subject to the exclusive jurisdiction of the Federal Courts 57 // of the Northern District of California (or, absent subject matter 58 // jurisdiction in such courts, the courts of the State of California), with 59 // venue lying exclusively in Santa Clara County, California. 60 61 // Copyright (c) 2001-2004, Hewlett-Packard Development Company, L.P. 62 // 63 // Permission is granted free of charge to copy, modify, use and distribute 64 // this software provided you include the entirety of this notice in all 65 // copies made. 66 // 67 // THIS SOFTWARE IS PROVIDED ON AN AS IS BASIS, WITHOUT WARRANTY OF ANY 68 // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, 69 // WARRANTIES THAT THE SUBJECT SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT 70 // FOR A PARTICULAR PURPOSE OR NON-INFRINGING. HEWLETT-PACKARD ASSUMES 71 // NO RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE. 72 // SHOULD THE SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, 73 // HEWLETT-PACKARD ASSUMES NO COST OR LIABILITY FOR ANY 74 // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES 75 // AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY SUBJECT SOFTWARE IS 76 // AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. 77 // 78 // UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING, 79 // WITHOUT LIMITATION, NEGLIGENCE OR STRICT LIABILITY), CONTRACT, OR 80 // OTHERWISE, SHALL HEWLETT-PACKARD BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, 81 // INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER WITH RESPECT TO THE 82 // SOFTWARE INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK 83 // STOPPAGE, LOSS OF DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL 84 // OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF HEWLETT-PACKARD SHALL 85 // HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. 86 // THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY RESULTING 87 // FROM HEWLETT-PACKARD's NEGLIGENCE TO THE EXTENT APPLICABLE 88 // LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE 89 // EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THAT 90 // EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. 91 // 92 93 // Added valueOf(string, radix), fixed some documentation comments. 94 // Hans_Boehm@hp.com 1/12/2001 95 // Fixed a serious typo in inv_CR(): For negative arguments it produced 96 // the wrong sign. This affected the sign of divisions. 97 // Added byteValue and fixed some comments. Hans.Boehm@hp.com 12/17/2002 98 // Added toStringFloatRep. Hans.Boehm@hp.com 4/1/2004 99 // Added get_appr() synchronization to allow access from multiple threads 100 // hboehm@google.com 4/25/2014 101 // Changed cos() prescaling to avoid logarithmic depth tree. 102 // hboehm@google.com 6/30/2014 103 // Added explicit asin() implementation. Remove one. Add ZERO and ONE and 104 // make them public. hboehm@google.com 5/21/2015 105 // Added Gauss-Legendre PI implementation. Removed two. 106 // hboehm@google.com 4/12/2016 107 // Fix shift operation in doubleValue. That produced incorrect values for 108 // large negative exponents. 109 // Don't negate argument and compute inverse for exp(). That causes severe 110 // performance problems for (-huge).exp() 111 // hboehm@google.com 8/21/2017 112 // Have comparison check for interruption. hboehm@google.com 10/31/2017 113 // Fix precision overflow issue in most general compareTo function. 114 // Fix a couple of unused variable bugs. Notably selector_sign was 115 // accidentally locally redeclared. (This turns out to be safe but useless.) 116 // hboehm@google.com 11/20/2018. 117 // Fix an exception-safety issue in gl_pi_CR.approximate. 118 // hboehm@google.com 3/3/2019. 119 // Near-overflow floating point exponents were not handled correctly in 120 // doubleValue(). Fixed. 121 // hboehm@google.com 7/23/2019. 122 123 package com.hp.creals; 124 125 import java.math.BigInteger; 126 import java.util.ArrayList; 127 128 /** 129 * Constructive real numbers, also known as recursive, or computable reals. 130 * Each recursive real number is represented as an object that provides an 131 * approximation function for the real number. 132 * The approximation function guarantees that the generated approximation 133 * is accurate to the specified precision. 134 * Arithmetic operations on constructive reals produce new such objects; 135 * they typically do not perform any real computation. 136 * In this sense, arithmetic computations are exact: They produce 137 * a description which describes the exact answer, and can be used to 138 * later approximate it to arbitrary precision. 139 * <P> 140 * When approximations are generated, <I>e.g.</i> for output, they are 141 * accurate to the requested precision; no cumulative rounding errors 142 * are visible. 143 * In order to achieve this precision, the approximation function will often 144 * need to approximate subexpressions to greater precision than was originally 145 * demanded. Thus the approximation of a constructive real number 146 * generated through a complex sequence of operations may eventually require 147 * evaluation to very high precision. This usually makes such computations 148 * prohibitively expensive for large numerical problems. 149 * But it is perfectly appropriate for use in a desk calculator, 150 * for small numerical problems, for the evaluation of expressions 151 * computated by a symbolic algebra system, for testing of accuracy claims 152 * for floating point code on small inputs, or the like. 153 * <P> 154 * We expect that the vast majority of uses will ignore the particular 155 * implementation, and the member functons <TT>approximate</tt> 156 * and <TT>get_appr</tt>. Such applications will treat <TT>CR</tt> as 157 * a conventional numerical type, with an interface modelled on 158 * <TT>java.math.BigInteger</tt>. No subclasses of <TT>CR</tt> 159 * will be explicitly mentioned by such a program. 160 * <P> 161 * All standard arithmetic operations, as well as a few algebraic 162 * and transcendal functions are provided. Constructive reals are 163 * immutable; thus all of these operations return a new constructive real. 164 * <P> 165 * A few uses will require explicit construction of approximation functions. 166 * The requires the construction of a subclass of <TT>CR</tt> with 167 * an overridden <TT>approximate</tt> function. Note that <TT>approximate</tt> 168 * should only be defined, but never called. <TT>get_appr</tt> 169 * provides the same functionality, but adds the caching necessary to obtain 170 * reasonable performance. 171 * <P> 172 * Any operation may throw <TT>com.hp.creals.AbortedException</tt> if the thread 173 * in which it is executing is interrupted. (<TT>InterruptedException</tt> 174 * cannot be used for this purpose, since CR inherits from <TT>Number</tt>.) 175 * <P> 176 * Any operation may also throw <TT>com.hp.creals.PrecisionOverflowException</tt> 177 * If the precision request generated during any subcalculation overflows 178 * a 28-bit integer. (This should be extremely unlikely, except as an 179 * outcome of a division by zero, or other erroneous computation.) 180 * 181 */ 182 public abstract class CR extends Number { 183 // CR is the basic representation of a number. 184 // Abstractly this is a function for computing an approximation 185 // plus the current best approximation. 186 // We could do without the latter, but that would 187 // be atrociously slow. 188 189 /** 190 * Indicates a constructive real operation was interrupted. 191 * Most constructive real operations may throw such an exception. 192 * This is unchecked, since Number methods may not raise checked 193 * exceptions. 194 */ 195 public static class AbortedException extends RuntimeException { AbortedException()196 public AbortedException() { super(); } AbortedException(String s)197 public AbortedException(String s) { super(s); } 198 } 199 200 /** 201 * Indicates that the number of bits of precision requested by 202 * a computation on constructive reals required more than 28 bits, 203 * and was thus in danger of overflowing an int. 204 * This is likely to be a symptom of a diverging computation, 205 * <I>e.g.</i> division by zero. 206 */ 207 public static class PrecisionOverflowException extends RuntimeException { PrecisionOverflowException()208 public PrecisionOverflowException() { super(); } PrecisionOverflowException(String s)209 public PrecisionOverflowException(String s) { super(s); } 210 } 211 212 // First some frequently used constants, so we don't have to 213 // recompute these all over the place. 214 static final BigInteger big0 = BigInteger.ZERO; 215 static final BigInteger big1 = BigInteger.ONE; 216 static final BigInteger bigm1 = BigInteger.valueOf(-1); 217 static final BigInteger big2 = BigInteger.valueOf(2); 218 static final BigInteger bigm2 = BigInteger.valueOf(-2); 219 static final BigInteger big3 = BigInteger.valueOf(3); 220 static final BigInteger big6 = BigInteger.valueOf(6); 221 static final BigInteger big8 = BigInteger.valueOf(8); 222 static final BigInteger big10 = BigInteger.TEN; 223 static final BigInteger big750 = BigInteger.valueOf(750); 224 static final BigInteger bigm750 = BigInteger.valueOf(-750); 225 226 /** 227 * Setting this to true requests that all computations be aborted by 228 * throwing AbortedException. Must be rest to false before any further 229 * computation. Ideally Thread.interrupt() should be used instead, but 230 * that doesn't appear to be consistently supported by browser VMs. 231 */ 232 public volatile static boolean please_stop = false; 233 234 /** 235 * Must be defined in subclasses of <TT>CR</tt>. 236 * Most users can ignore the existence of this method, and will 237 * not ever need to define a <TT>CR</tt> subclass. 238 * Returns value / 2 ** precision rounded to an integer. 239 * The error in the result is strictly < 1. 240 * Informally, approximate(n) gives a scaled approximation 241 * accurate to 2**n. 242 * Implementations may safely assume that precision is 243 * at least a factor of 8 away from overflow. 244 * Called only with the lock on the <TT>CR</tt> object 245 * already held. 246 */ approximate(int precision)247 protected abstract BigInteger approximate(int precision); 248 transient int min_prec; 249 // The smallest precision value with which the above 250 // has been called. 251 transient BigInteger max_appr; 252 // The scaled approximation corresponding to min_prec. 253 transient boolean appr_valid = false; 254 // min_prec and max_val are valid. 255 256 // Helper functions bound_log2(int n)257 static int bound_log2(int n) { 258 int abs_n = Math.abs(n); 259 return (int)Math.ceil(Math.log((double)(abs_n + 1))/Math.log(2.0)); 260 } 261 // Check that a precision is at least a factor of 8 away from 262 // overflowng the integer used to hold a precision spec. 263 // We generally perform this check early on, and then convince 264 // ourselves that none of the operations performed on precisions 265 // inside a function can generate an overflow. check_prec(int n)266 static void check_prec(int n) { 267 int high = n >> 28; 268 // if n is not in danger of overflowing, then the 4 high order 269 // bits should be identical. Thus high is either 0 or -1. 270 // The rest of this is to test for either of those in a way 271 // that should be as cheap as possible. 272 int high_shifted = n >> 29; 273 if (0 != (high ^ high_shifted)) { 274 throw new PrecisionOverflowException(); 275 } 276 } 277 278 /** 279 * The constructive real number corresponding to a 280 * <TT>BigInteger</tt>. 281 */ valueOf(BigInteger n)282 public static CR valueOf(BigInteger n) { 283 return new int_CR(n); 284 } 285 286 /** 287 * The constructive real number corresponding to a 288 * Java <TT>int</tt>. 289 */ valueOf(int n)290 public static CR valueOf(int n) { 291 return valueOf(BigInteger.valueOf(n)); 292 } 293 294 /** 295 * The constructive real number corresponding to a 296 * Java <TT>long</tt>. 297 */ valueOf(long n)298 public static CR valueOf(long n) { 299 return valueOf(BigInteger.valueOf(n)); 300 } 301 302 /** 303 * The constructive real number corresponding to a 304 * Java <TT>double</tt>. 305 * The result is undefined if argument is infinite or NaN. 306 */ valueOf(double n)307 public static CR valueOf(double n) { 308 if (Double.isNaN(n)) throw new ArithmeticException("Nan argument"); 309 if (Double.isInfinite(n)) { 310 throw new ArithmeticException("Infinite argument"); 311 } 312 boolean negative = (n < 0.0); 313 long bits = Double.doubleToLongBits(Math.abs(n)); 314 long mantissa = (bits & 0xfffffffffffffL); 315 int biased_exp = (int)(bits >> 52); 316 int exp = biased_exp - 1075; 317 if (biased_exp != 0) { 318 mantissa += (1L << 52); 319 } else { 320 mantissa <<= 1; 321 } 322 CR result = valueOf(mantissa).shiftLeft(exp); 323 if (negative) result = result.negate(); 324 return result; 325 } 326 327 /** 328 * The constructive real number corresponding to a 329 * Java <TT>float</tt>. 330 * The result is undefined if argument is infinite or NaN. 331 */ valueOf(float n)332 public static CR valueOf(float n) { 333 return valueOf((double) n); 334 } 335 336 public static CR ZERO = valueOf(0); 337 public static CR ONE = valueOf(1); 338 339 // Multiply k by 2**n. shift(BigInteger k, int n)340 static BigInteger shift(BigInteger k, int n) { 341 if (n == 0) return k; 342 if (n < 0) return k.shiftRight(-n); 343 return k.shiftLeft(n); 344 } 345 346 // Multiply by 2**n, rounding result scale(BigInteger k, int n)347 static BigInteger scale(BigInteger k, int n) { 348 if (n >= 0) { 349 return k.shiftLeft(n); 350 } else { 351 BigInteger adj_k = shift(k, n+1).add(big1); 352 return adj_k.shiftRight(1); 353 } 354 } 355 356 // Identical to approximate(), but maintain and update cache. 357 /** 358 * Returns value / 2 ** prec rounded to an integer. 359 * The error in the result is strictly < 1. 360 * Produces the same answer as <TT>approximate</tt>, but uses and 361 * maintains a cached approximation. 362 * Normally not overridden, and called only from <TT>approximate</tt> 363 * methods in subclasses. Not needed if the provided operations 364 * on constructive reals suffice. 365 */ get_appr(int precision)366 public synchronized BigInteger get_appr(int precision) { 367 check_prec(precision); 368 if (appr_valid && precision >= min_prec) { 369 return scale(max_appr, min_prec - precision); 370 } else { 371 BigInteger result = approximate(precision); 372 min_prec = precision; 373 max_appr = result; 374 appr_valid = true; 375 return result; 376 } 377 } 378 379 // Return the position of the msd. 380 // If x.msd() == n then 381 // 2**(n-1) < abs(x) < 2**(n+1) 382 // This initial version assumes that max_appr is valid 383 // and sufficiently removed from zero 384 // that the msd is determined. known_msd()385 int known_msd() { 386 int first_digit; 387 int length; 388 if (max_appr.signum() >= 0) { 389 length = max_appr.bitLength(); 390 } else { 391 length = max_appr.negate().bitLength(); 392 } 393 first_digit = min_prec + length - 1; 394 return first_digit; 395 } 396 397 // This version may return Integer.MIN_VALUE if the correct 398 // answer is < n. msd(int n)399 int msd(int n) { 400 if (!appr_valid || 401 max_appr.compareTo(big1) <= 0 402 && max_appr.compareTo(bigm1) >= 0) { 403 get_appr(n - 1); 404 if (max_appr.abs().compareTo(big1) <= 0) { 405 // msd could still be arbitrarily far to the right. 406 return Integer.MIN_VALUE; 407 } 408 } 409 return known_msd(); 410 } 411 412 413 // Functionally equivalent, but iteratively evaluates to higher 414 // precision. iter_msd(int n)415 int iter_msd(int n) 416 { 417 int prec = 0; 418 419 for (; prec > n + 30; prec = (prec * 3)/2 - 16) { 420 int msd = msd(prec); 421 if (msd != Integer.MIN_VALUE) return msd; 422 check_prec(prec); 423 if (Thread.interrupted() || please_stop) { 424 throw new AbortedException(); 425 } 426 } 427 return msd(n); 428 } 429 430 // This version returns a correct answer eventually, except 431 // that it loops forever (or throws an exception when the 432 // requested precision overflows) if this constructive real is zero. msd()433 int msd() { 434 return iter_msd(Integer.MIN_VALUE); 435 } 436 437 // A helper function for toString. 438 // Generate a String containing n zeroes. zeroes(int n)439 private static String zeroes(int n) { 440 char[] a = new char[n]; 441 for (int i = 0; i < n; ++i) { 442 a[i] = '0'; 443 } 444 return new String(a); 445 } 446 447 // Natural log of 2. Needed for some prescaling below. 448 // ln(2) = 7ln(10/9) - 2ln(25/24) + 3ln(81/80) simple_ln()449 CR simple_ln() { 450 return new prescaled_ln_CR(this.subtract(ONE)); 451 } 452 static CR ten_ninths = valueOf(10).divide(valueOf(9)); 453 static CR twentyfive_twentyfourths = valueOf(25).divide(valueOf(24)); 454 static CR eightyone_eightyeths = valueOf(81).divide(valueOf(80)); 455 static CR ln2_1 = valueOf(7).multiply(ten_ninths.simple_ln()); 456 static CR ln2_2 = 457 valueOf(2).multiply(twentyfive_twentyfourths.simple_ln()); 458 static CR ln2_3 = valueOf(3).multiply(eightyone_eightyeths.simple_ln()); 459 static CR ln2 = ln2_1.subtract(ln2_2).add(ln2_3); 460 461 // Atan of integer reciprocal. Used for atan_PI. Could perhaps be made 462 // public. atan_reciprocal(int n)463 static CR atan_reciprocal(int n) { 464 return new integral_atan_CR(n); 465 } 466 // Other constants used for PI computation. 467 static CR four = valueOf(4); 468 469 // Public operations. 470 /** 471 * Return 0 if x = y to within the indicated tolerance, 472 * -1 if x < y, and +1 if x > y. If x and y are indeed 473 * equal, it is guaranteed that 0 will be returned. If 474 * they differ by less than the tolerance, anything 475 * may happen. The tolerance allowed is 476 * the maximum of (abs(this)+abs(x))*(2**r) and 2**a 477 * @param x The other constructive real 478 * @param r Relative tolerance in bits 479 * @param a Absolute tolerance in bits 480 */ compareTo(CR x, int r, int a)481 public int compareTo(CR x, int r, int a) { 482 int this_msd = iter_msd(a); 483 int x_msd = x.iter_msd(this_msd > a? this_msd : a); 484 int max_msd = (x_msd > this_msd? x_msd : this_msd); 485 if (max_msd == Integer.MIN_VALUE) { 486 return 0; 487 } 488 check_prec(r); 489 int rel = max_msd + r; 490 int abs_prec = (rel > a? rel : a); 491 return compareTo(x, abs_prec); 492 } 493 494 /** 495 * Approximate comparison with only an absolute tolerance. 496 * Identical to the three argument version, but without a relative 497 * tolerance. 498 * Result is 0 if both constructive reals are equal, indeterminate 499 * if they differ by less than 2**a. 500 * 501 * @param x The other constructive real 502 * @param a Absolute tolerance in bits 503 */ compareTo(CR x, int a)504 public int compareTo(CR x, int a) { 505 int needed_prec = a - 1; 506 BigInteger this_appr = get_appr(needed_prec); 507 BigInteger x_appr = x.get_appr(needed_prec); 508 int comp1 = this_appr.compareTo(x_appr.add(big1)); 509 if (comp1 > 0) return 1; 510 int comp2 = this_appr.compareTo(x_appr.subtract(big1)); 511 if (comp2 < 0) return -1; 512 return 0; 513 } 514 515 /** 516 * Return -1 if <TT>this < x</tt>, or +1 if <TT>this > x</tt>. 517 * Should be called only if <TT>this != x</tt>. 518 * If <TT>this == x</tt>, this will not terminate correctly; typically it 519 * will run until it exhausts memory. 520 * If the two constructive reals may be equal, the two or 3 argument 521 * version of compareTo should be used. 522 */ compareTo(CR x)523 public int compareTo(CR x) { 524 for (int a = -20; ; a *= 2) { 525 check_prec(a); 526 int result = compareTo(x, a); 527 if (0 != result) return result; 528 if (Thread.interrupted() || please_stop) { 529 throw new AbortedException(); 530 } 531 } 532 } 533 534 /** 535 * Equivalent to <TT>compareTo(CR.valueOf(0), a)</tt> 536 */ signum(int a)537 public int signum(int a) { 538 if (appr_valid) { 539 int quick_try = max_appr.signum(); 540 if (0 != quick_try) return quick_try; 541 } 542 int needed_prec = a - 1; 543 BigInteger this_appr = get_appr(needed_prec); 544 return this_appr.signum(); 545 } 546 547 /** 548 * Return -1 if negative, +1 if positive. 549 * Should be called only if <TT>this != 0</tt>. 550 * In the 0 case, this will not terminate correctly; typically it 551 * will run until it exhausts memory. 552 * If the two constructive reals may be equal, the one or two argument 553 * version of signum should be used. 554 */ signum()555 public int signum() { 556 for (int a = -20; ; a *= 2) { 557 check_prec(a); 558 int result = signum(a); 559 if (0 != result) return result; 560 if (Thread.interrupted() || please_stop) { 561 throw new AbortedException(); 562 } 563 } 564 } 565 566 /** 567 * Return the constructive real number corresponding to the given 568 * textual representation and radix. 569 * 570 * @param s [-] digit* [. digit*] 571 * @param radix 572 */ 573 valueOf(String s, int radix)574 public static CR valueOf(String s, int radix) 575 throws NumberFormatException { 576 int len = s.length(); 577 int start_pos = 0, point_pos; 578 String fraction; 579 while (s.charAt(start_pos) == ' ') ++start_pos; 580 while (s.charAt(len - 1) == ' ') --len; 581 point_pos = s.indexOf('.', start_pos); 582 if (point_pos == -1) { 583 point_pos = len; 584 fraction = "0"; 585 } else { 586 fraction = s.substring(point_pos + 1, len); 587 } 588 String whole = s.substring(start_pos, point_pos); 589 BigInteger scaled_result = new BigInteger(whole + fraction, radix); 590 BigInteger divisor = BigInteger.valueOf(radix).pow(fraction.length()); 591 return CR.valueOf(scaled_result).divide(CR.valueOf(divisor)); 592 } 593 594 /** 595 * Return a textual representation accurate to <TT>n</tt> places 596 * to the right of the decimal point. <TT>n</tt> must be nonnegative. 597 * 598 * @param n Number of digits (>= 0) included to the right of decimal point 599 * @param radix Base ( >= 2, <= 16) for the resulting representation. 600 */ toString(int n, int radix)601 public String toString(int n, int radix) { 602 CR scaled_CR; 603 if (16 == radix) { 604 scaled_CR = shiftLeft(4*n); 605 } else { 606 BigInteger scale_factor = BigInteger.valueOf(radix).pow(n); 607 scaled_CR = multiply(new int_CR(scale_factor)); 608 } 609 BigInteger scaled_int = scaled_CR.get_appr(0); 610 String scaled_string = scaled_int.abs().toString(radix); 611 String result; 612 if (0 == n) { 613 result = scaled_string; 614 } else { 615 int len = scaled_string.length(); 616 if (len <= n) { 617 // Add sufficient leading zeroes 618 String z = zeroes(n + 1 - len); 619 scaled_string = z + scaled_string; 620 len = n + 1; 621 } 622 String whole = scaled_string.substring(0, len - n); 623 String fraction = scaled_string.substring(len - n); 624 result = whole + "." + fraction; 625 } 626 if (scaled_int.signum() < 0) { 627 result = "-" + result; 628 } 629 return result; 630 } 631 632 633 /** 634 * Equivalent to <TT>toString(n,10)</tt> 635 * 636 * @param n Number of digits included to the right of decimal point 637 */ toString(int n)638 public String toString(int n) { 639 return toString(n, 10); 640 } 641 642 /** 643 * Equivalent to <TT>toString(10, 10)</tt> 644 */ toString()645 public String toString() { 646 return toString(10); 647 } 648 649 static double doubleLog2 = Math.log(2.0); 650 /** 651 * Return a textual scientific notation representation accurate 652 * to <TT>n</tt> places to the right of the decimal point. 653 * <TT>n</tt> must be nonnegative. A value smaller than 654 * <TT>radix</tt>**-<TT>m</tt> may be displayed as 0. 655 * The <TT>mantissa</tt> component of the result is either "0" 656 * or exactly <TT>n</tt> digits long. The <TT>sign</tt> 657 * component is zero exactly when the mantissa is "0". 658 * 659 * @param n Number of digits (> 0) included to the right of decimal point. 660 * @param radix Base ( ≥ 2, ≤ 16) for the resulting representation. 661 * @param m Precision used to distinguish number from zero. 662 * Expressed as a power of m. 663 */ toStringFloatRep(int n, int radix, int m)664 public StringFloatRep toStringFloatRep(int n, int radix, int m) { 665 if (n <= 0) throw new ArithmeticException("Bad precision argument"); 666 double log2_radix = Math.log((double)radix)/doubleLog2; 667 BigInteger big_radix = BigInteger.valueOf(radix); 668 long long_msd_prec = (long)(log2_radix * (double)m); 669 if (long_msd_prec > (long)Integer.MAX_VALUE 670 || long_msd_prec < (long)Integer.MIN_VALUE) 671 throw new PrecisionOverflowException(); 672 int msd_prec = (int)long_msd_prec; 673 check_prec(msd_prec); 674 int msd = iter_msd(msd_prec - 2); 675 if (msd == Integer.MIN_VALUE) 676 return new StringFloatRep(0, "0", radix, 0); 677 int exponent = (int)Math.ceil((double)msd / log2_radix); 678 // Guess for the exponent. Try to get it usually right. 679 int scale_exp = exponent - n; 680 CR scale; 681 if (scale_exp > 0) { 682 scale = CR.valueOf(big_radix.pow(scale_exp)).inverse(); 683 } else { 684 scale = CR.valueOf(big_radix.pow(-scale_exp)); 685 } 686 CR scaled_res = multiply(scale); 687 BigInteger scaled_int = scaled_res.get_appr(0); 688 int sign = scaled_int.signum(); 689 String scaled_string = scaled_int.abs().toString(radix); 690 while (scaled_string.length() < n) { 691 // exponent was too large. Adjust. 692 scaled_res = scaled_res.multiply(CR.valueOf(big_radix)); 693 exponent -= 1; 694 scaled_int = scaled_res.get_appr(0); 695 sign = scaled_int.signum(); 696 scaled_string = scaled_int.abs().toString(radix); 697 } 698 if (scaled_string.length() > n) { 699 // exponent was too small. Adjust by truncating. 700 exponent += (scaled_string.length() - n); 701 scaled_string = scaled_string.substring(0, n); 702 } 703 return new StringFloatRep(sign, scaled_string, radix, exponent); 704 } 705 706 /** 707 * Return a BigInteger which differs by less than one from the 708 * constructive real. 709 */ BigIntegerValue()710 public BigInteger BigIntegerValue() { 711 return get_appr(0); 712 } 713 714 /** 715 * Return an int which differs by less than one from the 716 * constructive real. Behavior on overflow is undefined. 717 */ intValue()718 public int intValue() { 719 return BigIntegerValue().intValue(); 720 } 721 722 /** 723 * Return an int which differs by less than one from the 724 * constructive real. Behavior on overflow is undefined. 725 */ byteValue()726 public byte byteValue() { 727 return BigIntegerValue().byteValue(); 728 } 729 730 /** 731 * Return a long which differs by less than one from the 732 * constructive real. Behavior on overflow is undefined. 733 */ longValue()734 public long longValue() { 735 return BigIntegerValue().longValue(); 736 } 737 738 /** 739 * Return a double which differs by less than one in the least 740 * represented bit from the constructive real. 741 * (We're in fact closer to round-to-nearest than that, but we can't and 742 * don't promise correct rounding.) 743 */ doubleValue()744 public double doubleValue() { 745 int my_msd = iter_msd(-1080 /* slightly > exp. range */); 746 if (Integer.MIN_VALUE == my_msd) return 0.0; 747 int needed_prec = my_msd - 60; 748 double scaled_int = get_appr(needed_prec).doubleValue(); 749 boolean may_underflow = (needed_prec < -1000); 750 long scaled_int_rep = Double.doubleToLongBits(scaled_int); 751 long exp_adj = may_underflow? needed_prec + 96 : needed_prec; 752 long orig_exp = (scaled_int_rep >> 52) & 0x7ff; 753 // Original unbiased exponent is > 50. Exp_adj > -1050. 754 // Thus the sum must be > the smallest representable exponent 755 // of -1023. 756 if (orig_exp + exp_adj >= 0x7ff) { 757 // Exponent overflowed. 758 if (scaled_int < 0.0) { 759 return Double.NEGATIVE_INFINITY; 760 } else { 761 return Double.POSITIVE_INFINITY; 762 } 763 } 764 scaled_int_rep += exp_adj << 52; 765 double result = Double.longBitsToDouble(scaled_int_rep); 766 if (may_underflow) { 767 // Exponent is too large by 96. Compensate, relying on fp arithmetic 768 // to handle gradual underflow correctly. 769 double two48 = (double)(1L << 48); 770 return result/two48/two48; 771 } else { 772 return result; 773 } 774 } 775 776 /** 777 * Return a float which differs by less than one in the least 778 * represented bit from the constructive real. 779 */ floatValue()780 public float floatValue() { 781 return (float)doubleValue(); 782 // Note that double-rounding is not a problem here, since we 783 // cannot, and do not, guarantee correct rounding. 784 } 785 786 /** 787 * Add two constructive reals. 788 */ add(CR x)789 public CR add(CR x) { 790 return new add_CR(this, x); 791 } 792 793 /** 794 * Multiply a constructive real by 2**n. 795 * @param n shift count, may be negative 796 */ shiftLeft(int n)797 public CR shiftLeft(int n) { 798 check_prec(n); 799 return new shifted_CR(this, n); 800 } 801 802 /** 803 * Multiply a constructive real by 2**(-n). 804 * @param n shift count, may be negative 805 */ shiftRight(int n)806 public CR shiftRight(int n) { 807 check_prec(n); 808 return new shifted_CR(this, -n); 809 } 810 811 /** 812 * Produce a constructive real equivalent to the original, assuming 813 * the original was an integer. Undefined results if the original 814 * was not an integer. Prevents evaluation of digits to the right 815 * of the decimal point, and may thus improve performance. 816 */ assumeInt()817 public CR assumeInt() { 818 return new assumed_int_CR(this); 819 } 820 821 /** 822 * The additive inverse of a constructive real 823 */ negate()824 public CR negate() { 825 return new neg_CR(this); 826 } 827 828 /** 829 * The difference between two constructive reals 830 */ subtract(CR x)831 public CR subtract(CR x) { 832 return new add_CR(this, x.negate()); 833 } 834 835 /** 836 * The product of two constructive reals 837 */ multiply(CR x)838 public CR multiply(CR x) { 839 return new mult_CR(this, x); 840 } 841 842 /** 843 * The multiplicative inverse of a constructive real. 844 * <TT>x.inverse()</tt> is equivalent to <TT>CR.valueOf(1).divide(x)</tt>. 845 */ inverse()846 public CR inverse() { 847 return new inv_CR(this); 848 } 849 850 /** 851 * The quotient of two constructive reals. 852 */ divide(CR x)853 public CR divide(CR x) { 854 return new mult_CR(this, x.inverse()); 855 } 856 857 /** 858 * The real number <TT>x</tt> if <TT>this</tt> < 0, or <TT>y</tt> otherwise. 859 * Requires <TT>x</tt> = <TT>y</tt> if <TT>this</tt> = 0. 860 * Since comparisons may diverge, this is often 861 * a useful alternative to conditionals. 862 */ select(CR x, CR y)863 public CR select(CR x, CR y) { 864 return new select_CR(this, x, y); 865 } 866 867 /** 868 * The maximum of two constructive reals. 869 */ max(CR x)870 public CR max(CR x) { 871 return subtract(x).select(x, this); 872 } 873 874 /** 875 * The minimum of two constructive reals. 876 */ min(CR x)877 public CR min(CR x) { 878 return subtract(x).select(this, x); 879 } 880 881 /** 882 * The absolute value of a constructive reals. 883 * Note that this cannot be written as a conditional. 884 */ abs()885 public CR abs() { 886 return select(negate(), this); 887 } 888 889 /** 890 * The exponential function, that is e**<TT>this</tt>. 891 */ exp()892 public CR exp() { 893 final int low_prec = -10; 894 BigInteger rough_appr = get_appr(low_prec); 895 // Handle negative arguments directly; negating and computing inverse 896 // can be very expensive. 897 if (rough_appr.compareTo(big2) > 0 || rough_appr.compareTo(bigm2) < 0) { 898 CR square_root = shiftRight(1).exp(); 899 return square_root.multiply(square_root); 900 } else { 901 return new prescaled_exp_CR(this); 902 } 903 } 904 905 /** 906 * The ratio of a circle's circumference to its diameter. 907 */ 908 public static CR PI = new gl_pi_CR(); 909 910 // Our old PI implementation. Keep this around for now to allow checking. 911 // This implementation may also be faster for BigInteger implementations 912 // that support only quadratic multiplication, but exhibit high performance 913 // for small computations. (The standard Android 6 implementation supports 914 // subquadratic multiplication, but has high constant overhead.) Many other 915 // atan-based formulas are possible, but based on superficial 916 // experimentation, this is roughly as good as the more complex formulas. 917 public static CR atan_PI = four.multiply(four.multiply(atan_reciprocal(5)) 918 .subtract(atan_reciprocal(239))); 919 // pi/4 = 4*atan(1/5) - atan(1/239) 920 static CR half_pi = PI.shiftRight(1); 921 922 /** 923 * The trigonometric cosine function. 924 */ cos()925 public CR cos() { 926 BigInteger halfpi_multiples = divide(PI).get_appr(-1); 927 BigInteger abs_halfpi_multiples = halfpi_multiples.abs(); 928 if (abs_halfpi_multiples.compareTo(big2) >= 0) { 929 // Subtract multiples of PI 930 BigInteger pi_multiples = scale(halfpi_multiples, -1); 931 CR adjustment = PI.multiply(CR.valueOf(pi_multiples)); 932 if (pi_multiples.and(big1).signum() != 0) { 933 return subtract(adjustment).cos().negate(); 934 } else { 935 return subtract(adjustment).cos(); 936 } 937 } else if (get_appr(-1).abs().compareTo(big2) >= 0) { 938 // Scale further with double angle formula 939 CR cos_half = shiftRight(1).cos(); 940 return cos_half.multiply(cos_half).shiftLeft(1).subtract(ONE); 941 } else { 942 return new prescaled_cos_CR(this); 943 } 944 } 945 946 /** 947 * The trigonometric sine function. 948 */ sin()949 public CR sin() { 950 return half_pi.subtract(this).cos(); 951 } 952 953 /** 954 * The trignonometric arc (inverse) sine function. 955 */ asin()956 public CR asin() { 957 BigInteger rough_appr = get_appr(-10); 958 if (rough_appr.compareTo(big750) /* 1/sqrt(2) + a bit */ > 0){ 959 CR new_arg = ONE.subtract(multiply(this)).sqrt(); 960 return new_arg.acos(); 961 } else if (rough_appr.compareTo(bigm750) < 0) { 962 return negate().asin().negate(); 963 } else { 964 return new prescaled_asin_CR(this); 965 } 966 } 967 968 /** 969 * The trignonometric arc (inverse) cosine function. 970 */ acos()971 public CR acos() { 972 return half_pi.subtract(asin()); 973 } 974 975 static final BigInteger low_ln_limit = big8; /* sixteenths, i.e. 1/2 */ 976 static final BigInteger high_ln_limit = 977 BigInteger.valueOf(16 + 8 /* 1.5 */); 978 static final BigInteger scaled_4 = 979 BigInteger.valueOf(4*16); 980 981 /** 982 * The natural (base e) logarithm. 983 */ ln()984 public CR ln() { 985 final int low_prec = -4; 986 BigInteger rough_appr = get_appr(low_prec); /* In sixteenths */ 987 if (rough_appr.compareTo(big0) < 0) { 988 throw new ArithmeticException("ln(negative)"); 989 } 990 if (rough_appr.compareTo(low_ln_limit) <= 0) { 991 return inverse().ln().negate(); 992 } 993 if (rough_appr.compareTo(high_ln_limit) >= 0) { 994 if (rough_appr.compareTo(scaled_4) <= 0) { 995 CR quarter = sqrt().sqrt().ln(); 996 return quarter.shiftLeft(2); 997 } else { 998 int extra_bits = rough_appr.bitLength() - 3; 999 CR scaled_result = shiftRight(extra_bits).ln(); 1000 return scaled_result.add(CR.valueOf(extra_bits).multiply(ln2)); 1001 } 1002 } 1003 return simple_ln(); 1004 } 1005 1006 /** 1007 * The square root of a constructive real. 1008 */ sqrt()1009 public CR sqrt() { 1010 return new sqrt_CR(this); 1011 } 1012 1013 } // end of CR 1014 1015 1016 // 1017 // A specialization of CR for cases in which approximate() calls 1018 // to increase evaluation precision are somewhat expensive. 1019 // If we need to (re)evaluate, we speculatively evaluate to slightly 1020 // higher precision, miminimizing reevaluations. 1021 // Note that this requires any arguments to be evaluated to higher 1022 // precision than absolutely necessary. It can thus potentially 1023 // result in lots of wasted effort, and should be used judiciously. 1024 // This assumes that the order of magnitude of the number is roughly one. 1025 // 1026 abstract class slow_CR extends CR { 1027 static int max_prec = -64; 1028 static int prec_incr = 32; get_appr(int precision)1029 public synchronized BigInteger get_appr(int precision) { 1030 check_prec(precision); 1031 if (appr_valid && precision >= min_prec) { 1032 return scale(max_appr, min_prec - precision); 1033 } else { 1034 int eval_prec = (precision >= max_prec? max_prec : 1035 (precision - prec_incr + 1) & ~(prec_incr - 1)); 1036 BigInteger result = approximate(eval_prec); 1037 min_prec = eval_prec; 1038 max_appr = result; 1039 appr_valid = true; 1040 return scale(result, eval_prec - precision); 1041 } 1042 } 1043 } 1044 1045 1046 // Representation of an integer constant. Private. 1047 class int_CR extends CR { 1048 BigInteger value; int_CR(BigInteger n)1049 int_CR(BigInteger n) { 1050 value = n; 1051 } approximate(int p)1052 protected BigInteger approximate(int p) { 1053 return scale(value, -p) ; 1054 } 1055 } 1056 1057 // Representation of a number that may not have been completely 1058 // evaluated, but is assumed to be an integer. Hence we never 1059 // evaluate beyond the decimal point. 1060 class assumed_int_CR extends CR { 1061 CR value; assumed_int_CR(CR x)1062 assumed_int_CR(CR x) { 1063 value = x; 1064 } approximate(int p)1065 protected BigInteger approximate(int p) { 1066 if (p >= 0) { 1067 return value.get_appr(p); 1068 } else { 1069 return scale(value.get_appr(0), -p) ; 1070 } 1071 } 1072 } 1073 1074 // Representation of the sum of 2 constructive reals. Private. 1075 class add_CR extends CR { 1076 CR op1; 1077 CR op2; add_CR(CR x, CR y)1078 add_CR(CR x, CR y) { 1079 op1 = x; 1080 op2 = y; 1081 } approximate(int p)1082 protected BigInteger approximate(int p) { 1083 // Args need to be evaluated so that each error is < 1/4 ulp. 1084 // Rounding error from the cale call is <= 1/2 ulp, so that 1085 // final error is < 1 ulp. 1086 return scale(op1.get_appr(p-2).add(op2.get_appr(p-2)), -2); 1087 } 1088 } 1089 1090 // Representation of a CR multiplied by 2**n 1091 class shifted_CR extends CR { 1092 CR op; 1093 int count; shifted_CR(CR x, int n)1094 shifted_CR(CR x, int n) { 1095 op = x; 1096 count = n; 1097 } approximate(int p)1098 protected BigInteger approximate(int p) { 1099 return op.get_appr(p - count); 1100 } 1101 } 1102 1103 // Representation of the negation of a constructive real. Private. 1104 class neg_CR extends CR { 1105 CR op; neg_CR(CR x)1106 neg_CR(CR x) { 1107 op = x; 1108 } approximate(int p)1109 protected BigInteger approximate(int p) { 1110 return op.get_appr(p).negate(); 1111 } 1112 } 1113 1114 // Representation of: 1115 // op1 if selector < 0 1116 // op2 if selector >= 0 1117 // Assumes x = y if s = 0 1118 class select_CR extends CR { 1119 CR selector; 1120 int selector_sign; 1121 CR op1; 1122 CR op2; select_CR(CR s, CR x, CR y)1123 select_CR(CR s, CR x, CR y) { 1124 selector = s; 1125 selector_sign = selector.get_appr(-20).signum(); 1126 op1 = x; 1127 op2 = y; 1128 } approximate(int p)1129 protected BigInteger approximate(int p) { 1130 if (selector_sign < 0) return op1.get_appr(p); 1131 if (selector_sign > 0) return op2.get_appr(p); 1132 BigInteger op1_appr = op1.get_appr(p-1); 1133 BigInteger op2_appr = op2.get_appr(p-1); 1134 BigInteger diff = op1_appr.subtract(op2_appr).abs(); 1135 if (diff.compareTo(big1) <= 0) { 1136 // close enough; use either 1137 return scale(op1_appr, -1); 1138 } 1139 // op1 and op2 are different; selector != 0; 1140 // safe to get sign of selector. 1141 if (selector.signum() < 0) { 1142 selector_sign = -1; 1143 return scale(op1_appr, -1); 1144 } else { 1145 selector_sign = 1; 1146 return scale(op2_appr, -1); 1147 } 1148 } 1149 } 1150 1151 // Representation of the product of 2 constructive reals. Private. 1152 class mult_CR extends CR { 1153 CR op1; 1154 CR op2; mult_CR(CR x, CR y)1155 mult_CR(CR x, CR y) { 1156 op1 = x; 1157 op2 = y; 1158 } approximate(int p)1159 protected BigInteger approximate(int p) { 1160 int half_prec = (p >> 1) - 1; 1161 int msd_op1 = op1.msd(half_prec); 1162 int msd_op2; 1163 1164 if (msd_op1 == Integer.MIN_VALUE) { 1165 msd_op2 = op2.msd(half_prec); 1166 if (msd_op2 == Integer.MIN_VALUE) { 1167 // Product is small enough that zero will do as an 1168 // approximation. 1169 return big0; 1170 } else { 1171 // Swap them, so the larger operand (in absolute value) 1172 // is first. 1173 CR tmp; 1174 tmp = op1; 1175 op1 = op2; 1176 op2 = tmp; 1177 msd_op1 = msd_op2; 1178 } 1179 } 1180 // msd_op1 is valid at this point. 1181 int prec2 = p - msd_op1 - 3; // Precision needed for op2. 1182 // The appr. error is multiplied by at most 1183 // 2 ** (msd_op1 + 1) 1184 // Thus each approximation contributes 1/4 ulp 1185 // to the rounding error, and the final rounding adds 1186 // another 1/2 ulp. 1187 BigInteger appr2 = op2.get_appr(prec2); 1188 if (appr2.signum() == 0) return big0; 1189 msd_op2 = op2.known_msd(); 1190 int prec1 = p - msd_op2 - 3; // Precision needed for op1. 1191 BigInteger appr1 = op1.get_appr(prec1); 1192 int scale_digits = prec1 + prec2 - p; 1193 return scale(appr1.multiply(appr2), scale_digits); 1194 } 1195 } 1196 1197 // Representation of the multiplicative inverse of a constructive 1198 // real. Private. Should use Newton iteration to refine estimates. 1199 class inv_CR extends CR { 1200 CR op; inv_CR(CR x)1201 inv_CR(CR x) { op = x; } approximate(int p)1202 protected BigInteger approximate(int p) { 1203 int msd = op.msd(); 1204 int inv_msd = 1 - msd; 1205 int digits_needed = inv_msd - p + 3; 1206 // Number of SIGNIFICANT digits needed for 1207 // argument, excl. msd position, which may 1208 // be fictitious, since msd routine can be 1209 // off by 1. Roughly 1 extra digit is 1210 // needed since the relative error is the 1211 // same in the argument and result, but 1212 // this isn't quite the same as the number 1213 // of significant digits. Another digit 1214 // is needed to compensate for slop in the 1215 // calculation. 1216 // One further bit is required, since the 1217 // final rounding introduces a 0.5 ulp 1218 // error. 1219 int prec_needed = msd - digits_needed; 1220 int log_scale_factor = -p - prec_needed; 1221 if (log_scale_factor < 0) return big0; 1222 BigInteger dividend = big1.shiftLeft(log_scale_factor); 1223 BigInteger scaled_divisor = op.get_appr(prec_needed); 1224 BigInteger abs_scaled_divisor = scaled_divisor.abs(); 1225 BigInteger adj_dividend = dividend.add( 1226 abs_scaled_divisor.shiftRight(1)); 1227 // Adjustment so that final result is rounded. 1228 BigInteger result = adj_dividend.divide(abs_scaled_divisor); 1229 if (scaled_divisor.signum() < 0) { 1230 return result.negate(); 1231 } else { 1232 return result; 1233 } 1234 } 1235 } 1236 1237 1238 // Representation of the exponential of a constructive real. Private. 1239 // Uses a Taylor series expansion. Assumes |x| < 1/2. 1240 // Note: this is known to be a bad algorithm for 1241 // floating point. Unfortunately, other alternatives 1242 // appear to require precomputed information. 1243 class prescaled_exp_CR extends CR { 1244 CR op; prescaled_exp_CR(CR x)1245 prescaled_exp_CR(CR x) { op = x; } approximate(int p)1246 protected BigInteger approximate(int p) { 1247 if (p >= 1) return big0; 1248 int iterations_needed = -p/2 + 2; // conservative estimate > 0. 1249 // Claim: each intermediate term is accurate 1250 // to 2*2^calc_precision. 1251 // Total rounding error in series computation is 1252 // 2*iterations_needed*2^calc_precision, 1253 // exclusive of error in op. 1254 int calc_precision = p - bound_log2(2*iterations_needed) 1255 - 4; // for error in op, truncation. 1256 int op_prec = p - 3; 1257 BigInteger op_appr = op.get_appr(op_prec); 1258 // Error in argument results in error of < 3/8 ulp. 1259 // Sum of term eval. rounding error is < 1/16 ulp. 1260 // Series truncation error < 1/16 ulp. 1261 // Final rounding error is <= 1/2 ulp. 1262 // Thus final error is < 1 ulp. 1263 BigInteger scaled_1 = big1.shiftLeft(-calc_precision); 1264 BigInteger current_term = scaled_1; 1265 BigInteger current_sum = scaled_1; 1266 int n = 0; 1267 BigInteger max_trunc_error = 1268 big1.shiftLeft(p - 4 - calc_precision); 1269 while (current_term.abs().compareTo(max_trunc_error) >= 0) { 1270 if (Thread.interrupted() || please_stop) throw new AbortedException(); 1271 n += 1; 1272 /* current_term = current_term * op / n */ 1273 current_term = scale(current_term.multiply(op_appr), op_prec); 1274 current_term = current_term.divide(BigInteger.valueOf(n)); 1275 current_sum = current_sum.add(current_term); 1276 } 1277 return scale(current_sum, calc_precision - p); 1278 } 1279 } 1280 1281 // Representation of the cosine of a constructive real. Private. 1282 // Uses a Taylor series expansion. Assumes |x| < 1. 1283 class prescaled_cos_CR extends slow_CR { 1284 CR op; prescaled_cos_CR(CR x)1285 prescaled_cos_CR(CR x) { 1286 op = x; 1287 } approximate(int p)1288 protected BigInteger approximate(int p) { 1289 if (p >= 1) return big0; 1290 int iterations_needed = -p/2 + 4; // conservative estimate > 0. 1291 // Claim: each intermediate term is accurate 1292 // to 2*2^calc_precision. 1293 // Total rounding error in series computation is 1294 // 2*iterations_needed*2^calc_precision, 1295 // exclusive of error in op. 1296 int calc_precision = p - bound_log2(2*iterations_needed) 1297 - 4; // for error in op, truncation. 1298 int op_prec = p - 2; 1299 BigInteger op_appr = op.get_appr(op_prec); 1300 // Error in argument results in error of < 1/4 ulp. 1301 // Cumulative arithmetic rounding error is < 1/16 ulp. 1302 // Series truncation error < 1/16 ulp. 1303 // Final rounding error is <= 1/2 ulp. 1304 // Thus final error is < 1 ulp. 1305 BigInteger current_term; 1306 int n; 1307 BigInteger max_trunc_error = 1308 big1.shiftLeft(p - 4 - calc_precision); 1309 n = 0; 1310 current_term = big1.shiftLeft(-calc_precision); 1311 BigInteger current_sum = current_term; 1312 while (current_term.abs().compareTo(max_trunc_error) >= 0) { 1313 if (Thread.interrupted() || please_stop) throw new AbortedException(); 1314 n += 2; 1315 /* current_term = - current_term * op * op / n * (n - 1) */ 1316 current_term = scale(current_term.multiply(op_appr), op_prec); 1317 current_term = scale(current_term.multiply(op_appr), op_prec); 1318 BigInteger divisor = BigInteger.valueOf(-n) 1319 .multiply(BigInteger.valueOf(n-1)); 1320 current_term = current_term.divide(divisor); 1321 current_sum = current_sum.add(current_term); 1322 } 1323 return scale(current_sum, calc_precision - p); 1324 } 1325 } 1326 1327 // The constructive real atan(1/n), where n is a small integer 1328 // > base. 1329 // This gives a simple and moderately fast way to compute PI. 1330 class integral_atan_CR extends slow_CR { 1331 int op; integral_atan_CR(int x)1332 integral_atan_CR(int x) { op = x; } approximate(int p)1333 protected BigInteger approximate(int p) { 1334 if (p >= 1) return big0; 1335 int iterations_needed = -p/2 + 2; // conservative estimate > 0. 1336 // Claim: each intermediate term is accurate 1337 // to 2*base^calc_precision. 1338 // Total rounding error in series computation is 1339 // 2*iterations_needed*base^calc_precision, 1340 // exclusive of error in op. 1341 int calc_precision = p - bound_log2(2*iterations_needed) 1342 - 2; // for error in op, truncation. 1343 // Error in argument results in error of < 3/8 ulp. 1344 // Cumulative arithmetic rounding error is < 1/4 ulp. 1345 // Series truncation error < 1/4 ulp. 1346 // Final rounding error is <= 1/2 ulp. 1347 // Thus final error is < 1 ulp. 1348 BigInteger scaled_1 = big1.shiftLeft(-calc_precision); 1349 BigInteger big_op = BigInteger.valueOf(op); 1350 BigInteger big_op_squared = BigInteger.valueOf(op*op); 1351 BigInteger op_inverse = scaled_1.divide(big_op); 1352 BigInteger current_power = op_inverse; 1353 BigInteger current_term = op_inverse; 1354 BigInteger current_sum = op_inverse; 1355 int current_sign = 1; 1356 int n = 1; 1357 BigInteger max_trunc_error = 1358 big1.shiftLeft(p - 2 - calc_precision); 1359 while (current_term.abs().compareTo(max_trunc_error) >= 0) { 1360 if (Thread.interrupted() || please_stop) throw new AbortedException(); 1361 n += 2; 1362 current_power = current_power.divide(big_op_squared); 1363 current_sign = -current_sign; 1364 current_term = 1365 current_power.divide(BigInteger.valueOf(current_sign*n)); 1366 current_sum = current_sum.add(current_term); 1367 } 1368 return scale(current_sum, calc_precision - p); 1369 } 1370 } 1371 1372 // Representation for ln(1 + op) 1373 class prescaled_ln_CR extends slow_CR { 1374 CR op; prescaled_ln_CR(CR x)1375 prescaled_ln_CR(CR x) { op = x; } 1376 // Compute an approximation of ln(1+x) to precision 1377 // prec. This assumes |x| < 1/2. 1378 // It uses a Taylor series expansion. 1379 // Unfortunately there appears to be no way to take 1380 // advantage of old information. 1381 // Note: this is known to be a bad algorithm for 1382 // floating point. Unfortunately, other alternatives 1383 // appear to require precomputed tabular information. approximate(int p)1384 protected BigInteger approximate(int p) { 1385 if (p >= 0) return big0; 1386 int iterations_needed = -p; // conservative estimate > 0. 1387 // Claim: each intermediate term is accurate 1388 // to 2*2^calc_precision. Total error is 1389 // 2*iterations_needed*2^calc_precision 1390 // exclusive of error in op. 1391 int calc_precision = p - bound_log2(2*iterations_needed) 1392 - 4; // for error in op, truncation. 1393 int op_prec = p - 3; 1394 BigInteger op_appr = op.get_appr(op_prec); 1395 // Error analysis as for exponential. 1396 BigInteger x_nth = scale(op_appr, op_prec - calc_precision); 1397 BigInteger current_term = x_nth; // x**n 1398 BigInteger current_sum = current_term; 1399 int n = 1; 1400 int current_sign = 1; // (-1)^(n-1) 1401 BigInteger max_trunc_error = 1402 big1.shiftLeft(p - 4 - calc_precision); 1403 while (current_term.abs().compareTo(max_trunc_error) >= 0) { 1404 if (Thread.interrupted() || please_stop) throw new AbortedException(); 1405 n += 1; 1406 current_sign = -current_sign; 1407 x_nth = scale(x_nth.multiply(op_appr), op_prec); 1408 current_term = x_nth.divide(BigInteger.valueOf(n * current_sign)); 1409 // x**n / (n * (-1)**(n-1)) 1410 current_sum = current_sum.add(current_term); 1411 } 1412 return scale(current_sum, calc_precision - p); 1413 } 1414 } 1415 1416 // Representation of the arcsine of a constructive real. Private. 1417 // Uses a Taylor series expansion. Assumes |x| < (1/2)^(1/3). 1418 class prescaled_asin_CR extends slow_CR { 1419 CR op; prescaled_asin_CR(CR x)1420 prescaled_asin_CR(CR x) { 1421 op = x; 1422 } approximate(int p)1423 protected BigInteger approximate(int p) { 1424 // The Taylor series is the sum of x^(2n+1) * (2n)!/(4^n n!^2 (2n+1)) 1425 // Note that (2n)!/(4^n n!^2) is always less than one. 1426 // (The denominator is effectively 2n*2n*(2n-2)*(2n-2)*...*2*2 1427 // which is clearly > (2n)!) 1428 // Thus all terms are bounded by x^(2n+1). 1429 // Unfortunately, there's no easy way to prescale the argument 1430 // to less than 1/sqrt(2), and we can only approximate that. 1431 // Thus the worst case iteration count is fairly high. 1432 // But it doesn't make much difference. 1433 if (p >= 2) return big0; // Never bigger than 4. 1434 int iterations_needed = -3 * p / 2 + 4; 1435 // conservative estimate > 0. 1436 // Follows from assumed bound on x and 1437 // the fact that only every other Taylor 1438 // Series term is present. 1439 // Claim: each intermediate term is accurate 1440 // to 2*2^calc_precision. 1441 // Total rounding error in series computation is 1442 // 2*iterations_needed*2^calc_precision, 1443 // exclusive of error in op. 1444 int calc_precision = p - bound_log2(2*iterations_needed) 1445 - 4; // for error in op, truncation. 1446 int op_prec = p - 3; // always <= -2 1447 BigInteger op_appr = op.get_appr(op_prec); 1448 // Error in argument results in error of < 1/4 ulp. 1449 // (Derivative is bounded by 2 in the specified range and we use 1450 // 3 extra digits.) 1451 // Ignoring the argument error, each term has an error of 1452 // < 3ulps relative to calc_precision, which is more precise than p. 1453 // Cumulative arithmetic rounding error is < 3/16 ulp (relative to p). 1454 // Series truncation error < 2/16 ulp. (Each computed term 1455 // is at most 2/3 of last one, so some of remaining series < 1456 // 3/2 * current term.) 1457 // Final rounding error is <= 1/2 ulp. 1458 // Thus final error is < 1 ulp (relative to p). 1459 BigInteger max_last_term = 1460 big1.shiftLeft(p - 4 - calc_precision); 1461 int exp = 1; // Current exponent, = 2n+1 in above expression 1462 BigInteger current_term = op_appr.shiftLeft(op_prec - calc_precision); 1463 BigInteger current_sum = current_term; 1464 BigInteger current_factor = current_term; 1465 // Current scaled Taylor series term 1466 // before division by the exponent. 1467 // Accurate to 3 ulp at calc_precision. 1468 while (current_term.abs().compareTo(max_last_term) >= 0) { 1469 if (Thread.interrupted() || please_stop) throw new AbortedException(); 1470 exp += 2; 1471 // current_factor = current_factor * op * op * (exp-1) * (exp-2) / 1472 // (exp-1) * (exp-1), with the two exp-1 factors cancelling, 1473 // giving 1474 // current_factor = current_factor * op * op * (exp-2) / (exp-1) 1475 // Thus the error any in the previous term is multiplied by 1476 // op^2, adding an error of < (1/2)^(2/3) < 2/3 the original 1477 // error. 1478 current_factor = current_factor.multiply(BigInteger.valueOf(exp - 2)); 1479 current_factor = scale(current_factor.multiply(op_appr), op_prec + 2); 1480 // Carry 2 extra bits of precision forward; thus 1481 // this effectively introduces 1/8 ulp error. 1482 current_factor = current_factor.multiply(op_appr); 1483 BigInteger divisor = BigInteger.valueOf(exp - 1); 1484 current_factor = current_factor.divide(divisor); 1485 // Another 1/4 ulp error here. 1486 current_factor = scale(current_factor, op_prec - 2); 1487 // Remove extra 2 bits. 1/2 ulp rounding error. 1488 // Current_factor has original 3 ulp rounding error, which we 1489 // reduced by 1, plus < 1 ulp new rounding error. 1490 current_term = current_factor.divide(BigInteger.valueOf(exp)); 1491 // Contributes 1 ulp error to sum plus at most 3 ulp 1492 // from current_factor. 1493 current_sum = current_sum.add(current_term); 1494 } 1495 return scale(current_sum, calc_precision - p); 1496 } 1497 } 1498 1499 1500 class sqrt_CR extends CR { 1501 CR op; sqrt_CR(CR x)1502 sqrt_CR(CR x) { op = x; } 1503 // Explicitly provide an initial approximation. 1504 // Useful for arithmetic geometric mean algorithms, where we've previously 1505 // computed a very similar square root. sqrt_CR(CR x, int min_p, BigInteger max_a)1506 sqrt_CR(CR x, int min_p, BigInteger max_a) { 1507 op = x; 1508 min_prec = min_p; 1509 max_appr = max_a; 1510 appr_valid = true; 1511 } 1512 final int fp_prec = 50; // Conservative estimate of number of 1513 // significant bits in double precision 1514 // computation. 1515 final int fp_op_prec = 60; approximate(int p)1516 protected BigInteger approximate(int p) { 1517 int max_op_prec_needed = 2*p - 1; 1518 int msd = op.iter_msd(max_op_prec_needed); 1519 if (msd <= max_op_prec_needed) return big0; 1520 int result_msd = msd/2; // +- 1 1521 int result_digits = result_msd - p; // +- 2 1522 if (result_digits > fp_prec) { 1523 // Compute less precise approximation and use a Newton iter. 1524 int appr_digits = result_digits/2 + 6; 1525 // This should be conservative. Is fewer enough? 1526 int appr_prec = result_msd - appr_digits; 1527 int prod_prec = 2*appr_prec; 1528 // First compute the argument to maximal precision, so we don't end up 1529 // reevaluating it incrementally. 1530 BigInteger op_appr = op.get_appr(prod_prec); 1531 BigInteger last_appr = get_appr(appr_prec); 1532 // Compute (last_appr * last_appr + op_appr) / last_appr / 2 1533 // while adjusting the scaling to make everything work 1534 BigInteger prod_prec_scaled_numerator = 1535 last_appr.multiply(last_appr).add(op_appr); 1536 BigInteger scaled_numerator = 1537 scale(prod_prec_scaled_numerator, appr_prec - p); 1538 BigInteger shifted_result = scaled_numerator.divide(last_appr); 1539 return shifted_result.add(big1).shiftRight(1); 1540 } else { 1541 // Use a double precision floating point approximation. 1542 // Make sure all precisions are even 1543 int op_prec = (msd - fp_op_prec) & ~1; 1544 int working_prec = op_prec - fp_op_prec; 1545 BigInteger scaled_bi_appr = op.get_appr(op_prec) 1546 .shiftLeft(fp_op_prec); 1547 double scaled_appr = scaled_bi_appr.doubleValue(); 1548 if (scaled_appr < 0.0) 1549 throw new ArithmeticException("sqrt(negative)"); 1550 double scaled_fp_sqrt = Math.sqrt(scaled_appr); 1551 BigInteger scaled_sqrt = BigInteger.valueOf((long)scaled_fp_sqrt); 1552 int shift_count = working_prec/2 - p; 1553 return shift(scaled_sqrt, shift_count); 1554 } 1555 } 1556 } 1557 1558 // The constant PI, computed using the Gauss-Legendre alternating 1559 // arithmetic-geometric mean algorithm: 1560 // a[0] = 1 1561 // b[0] = 1/sqrt(2) 1562 // t[0] = 1/4 1563 // p[0] = 1 1564 // 1565 // a[n+1] = (a[n] + b[n])/2 (arithmetic mean, between 0.8 and 1) 1566 // b[n+1] = sqrt(a[n] * b[n]) (geometric mean, between 0.7 and 1) 1567 // t[n+1] = t[n] - (2^n)(a[n]-a[n+1])^2, (always between 0.2 and 0.25) 1568 // 1569 // pi is then approximated as (a[n+1]+b[n+1])^2 / 4*t[n+1]. 1570 // 1571 class gl_pi_CR extends slow_CR { 1572 // In addition to the best approximation kept by the CR base class, we keep 1573 // the entire sequence b[n], to the extent we've needed it so far. Each 1574 // reevaluation leads to slightly different sqrt arguments, but the 1575 // previous result can be used to avoid repeating low precision Newton 1576 // iterations for the sqrt approximation. 1577 ArrayList<Integer> b_prec = new ArrayList<Integer>(); 1578 ArrayList<BigInteger> b_val = new ArrayList<BigInteger>(); gl_pi_CR()1579 gl_pi_CR() { 1580 b_prec.add(null); // Zeroth entry unused. 1581 b_val.add(null); 1582 } 1583 private static BigInteger TOLERANCE = BigInteger.valueOf(4); 1584 // sqrt(1/2) 1585 private static CR SQRT_HALF = new sqrt_CR(ONE.shiftRight(1)); 1586 approximate(int p)1587 protected BigInteger approximate(int p) { 1588 // Get us back into a consistent state if the last computation 1589 // was interrupted after pushing onto b_prec. 1590 if (b_prec.size() > b_val.size()) { 1591 b_prec.remove(b_prec.size() - 1); 1592 } 1593 // Rough approximations are easy. 1594 if (p >= 0) return scale(BigInteger.valueOf(3), -p); 1595 // We need roughly log2(p) iterations. Each iteration should 1596 // contribute no more than 2 ulps to the error in the corresponding 1597 // term (a[n], b[n], or t[n]). Thus 2log2(n) bits plus a few for the 1598 // final calulation and rounding suffice. 1599 final int extra_eval_prec = 1600 (int)Math.ceil(Math.log(-p) / Math.log(2)) + 10; 1601 // All our terms are implicitly scaled by eval_prec. 1602 final int eval_prec = p - extra_eval_prec; 1603 BigInteger a = BigInteger.ONE.shiftLeft(-eval_prec); 1604 BigInteger b = SQRT_HALF.get_appr(eval_prec); 1605 BigInteger t = BigInteger.ONE.shiftLeft(-eval_prec - 2); 1606 int n = 0; 1607 while (a.subtract(b).subtract(TOLERANCE).signum() > 0) { 1608 // Current values correspond to n, next_ values to n + 1 1609 // b_prec.size() == b_val.size() >= n + 1 1610 final BigInteger next_a = a.add(b).shiftRight(1); 1611 final BigInteger next_b; 1612 final BigInteger a_diff = a.subtract(next_a); 1613 final BigInteger b_prod = a.multiply(b).shiftRight(-eval_prec); 1614 // We compute square root approximations using a nested 1615 // temporary CR computation, to avoid implementing BigInteger 1616 // square roots separately. 1617 final CR b_prod_as_CR = CR.valueOf(b_prod).shiftRight(-eval_prec); 1618 if (b_prec.size() == n + 1) { 1619 // Add an n+1st slot. 1620 // Take care to make this exception-safe; b_prec and b_val 1621 // must remain consistent, even if we are interrupted, or run 1622 // out of memory. It's OK to just push on b_prec in that case. 1623 final CR next_b_as_CR = b_prod_as_CR.sqrt(); 1624 next_b = next_b_as_CR.get_appr(eval_prec); 1625 final BigInteger scaled_next_b = scale(next_b, -extra_eval_prec); 1626 b_prec.add(p); 1627 b_val.add(scaled_next_b); 1628 } else { 1629 // Reuse previous approximation to reduce sqrt iterations, 1630 // hopefully to one. 1631 final CR next_b_as_CR = 1632 new sqrt_CR(b_prod_as_CR, 1633 b_prec.get(n + 1), b_val.get(n + 1)); 1634 next_b = next_b_as_CR.get_appr(eval_prec); 1635 // We assume that set() doesn't throw for any reason. 1636 b_prec.set(n + 1, p); 1637 b_val.set(n + 1, scale(next_b, -extra_eval_prec)); 1638 } 1639 // b_prec.size() == b_val.size() >= n + 2 1640 final BigInteger next_t = 1641 t.subtract(a_diff.multiply(a_diff) 1642 .shiftLeft(n + eval_prec)); // shift dist. usually neg. 1643 a = next_a; 1644 b = next_b; 1645 t = next_t; 1646 ++n; 1647 } 1648 final BigInteger sum = a.add(b); 1649 final BigInteger result = sum.multiply(sum).divide(t).shiftRight(2); 1650 return scale(result, -extra_eval_prec); 1651 } 1652 } 1653