1. /*
  2. * @(#)FloatingDecimal.java 1.15 01/11/29
  3. *
  4. * Copyright 2002 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.lang;
  8. class FloatingDecimal{
  9. boolean isExceptional;
  10. boolean isNegative;
  11. int decExponent;
  12. char digits[];
  13. int nDigits;
  14. int bigIntExp;
  15. int bigIntNBits;
  16. boolean mustSetRoundDir = false;
  17. int roundDir; // set by doubleValue
  18. private FloatingDecimal( boolean negSign, int decExponent, char []digits, int n, boolean e )
  19. {
  20. isNegative = negSign;
  21. isExceptional = e;
  22. this.decExponent = decExponent;
  23. this.digits = digits;
  24. this.nDigits = n;
  25. }
  26. /*
  27. * Constants of the implementation
  28. * Most are IEEE-754 related.
  29. * (There are more really boring constants at the end.)
  30. */
  31. static final long signMask = 0x8000000000000000L;
  32. static final long expMask = 0x7ff0000000000000L;
  33. static final long fractMask= ~(signMask|expMask);
  34. static final int expShift = 52;
  35. static final int expBias = 1023;
  36. static final long fractHOB = ( 1L<<expShift ); // assumed High-Order bit
  37. static final long expOne = ((long)expBias)<<expShift; // exponent of 1.0
  38. static final int maxSmallBinExp = 62;
  39. static final int minSmallBinExp = -( 63 / 3 );
  40. static final int maxDecimalDigits = 15;
  41. static final int maxDecimalExponent = 308;
  42. static final int minDecimalExponent = -324;
  43. static final int bigDecimalExponent = 324; // i.e. abs(minDecimalExponent)
  44. static final long highbyte = 0xff00000000000000L;
  45. static final long highbit = 0x8000000000000000L;
  46. static final long lowbytes = ~highbyte;
  47. static final int singleSignMask = 0x80000000;
  48. static final int singleExpMask = 0x7f800000;
  49. static final int singleFractMask = ~(singleSignMask|singleExpMask);
  50. static final int singleExpShift = 23;
  51. static final int singleFractHOB = 1<<singleExpShift;
  52. static final int singleExpBias = 127;
  53. static final int singleMaxDecimalDigits = 7;
  54. static final int singleMaxDecimalExponent = 38;
  55. static final int singleMinDecimalExponent = -45;
  56. static final int intDecimalDigits = 9;
  57. /*
  58. * count number of bits from high-order 1 bit to low-order 1 bit,
  59. * inclusive.
  60. */
  61. private static int
  62. countBits( long v ){
  63. //
  64. // the strategy is to shift until we get a non-zero sign bit
  65. // then shift until we have no bits left, counting the difference.
  66. // we do byte shifting as a hack. Hope it helps.
  67. //
  68. if ( v == 0L ) return 0;
  69. while ( ( v & highbyte ) == 0L ){
  70. v <<= 8;
  71. }
  72. while ( v > 0L ) { // i.e. while ((v&highbit) == 0L )
  73. v <<= 1;
  74. }
  75. int n = 0;
  76. while (( v & lowbytes ) != 0L ){
  77. v <<= 8;
  78. n += 8;
  79. }
  80. while ( v != 0L ){
  81. v <<= 1;
  82. n += 1;
  83. }
  84. return n;
  85. }
  86. /*
  87. * Keep big powers of 5 handy for future reference.
  88. */
  89. private static FDBigInt b5p[];
  90. private static synchronized FDBigInt
  91. big5pow( int p ){
  92. if ( p < 0 )
  93. throw new RuntimeException( "Assertion botch: negative power of 5");
  94. if ( b5p == null ){
  95. b5p = new FDBigInt[ p+1 ];
  96. }else if (b5p.length <= p ){
  97. FDBigInt t[] = new FDBigInt[ p+1 ];
  98. System.arraycopy( b5p, 0, t, 0, b5p.length );
  99. b5p = t;
  100. }
  101. if ( b5p[p] != null )
  102. return b5p[p];
  103. else if ( p < small5pow.length )
  104. return b5p[p] = new FDBigInt( small5pow[p] );
  105. else if ( p < long5pow.length )
  106. return b5p[p] = new FDBigInt( long5pow[p] );
  107. else {
  108. // construct the value.
  109. // recursively.
  110. int q, r;
  111. // in order to compute 5^p,
  112. // compute its square root, 5^(p/2) and square.
  113. // or, let q = p / 2, r = p -q, then
  114. // 5^p = 5^(q+r) = 5^q * 5^r
  115. q = p >> 1;
  116. r = p - q;
  117. FDBigInt bigq = b5p[q];
  118. if ( bigq == null )
  119. bigq = big5pow ( q );
  120. if ( r < small5pow.length ){
  121. return (b5p[p] = bigq.mult( small5pow[r] ) );
  122. }else{
  123. FDBigInt bigr = b5p[ r ];
  124. if ( bigr == null )
  125. bigr = big5pow( r );
  126. return (b5p[p] = bigq.mult( bigr ) );
  127. }
  128. }
  129. }
  130. //
  131. // a common operation
  132. //
  133. private static FDBigInt
  134. multPow52( FDBigInt v, int p5, int p2 ){
  135. if ( p5 != 0 ){
  136. if ( p5 < small5pow.length ){
  137. v = v.mult( small5pow[p5] );
  138. } else {
  139. v = v.mult( big5pow( p5 ) );
  140. }
  141. }
  142. if ( p2 != 0 ){
  143. v.lshiftMe( p2 );
  144. }
  145. return v;
  146. }
  147. //
  148. // another common operation
  149. //
  150. private static FDBigInt
  151. constructPow52( int p5, int p2 ){
  152. FDBigInt v = new FDBigInt( big5pow( p5 ) );
  153. if ( p2 != 0 ){
  154. v.lshiftMe( p2 );
  155. }
  156. return v;
  157. }
  158. /*
  159. * Make a floating double into a FDBigInt.
  160. * This could also be structured as a FDBigInt
  161. * constructor, but we'd have to build a lot of knowledge
  162. * about floating-point representation into it, and we don't want to.
  163. *
  164. * AS A SIDE EFFECT, THIS METHOD WILL SET THE INSTANCE VARIABLES
  165. * bigIntExp and bigIntNBits
  166. *
  167. */
  168. private FDBigInt
  169. doubleToBigInt( double dval ){
  170. long lbits = Double.doubleToLongBits( dval ) & ~signMask;
  171. int binexp = (int)(lbits >>> expShift);
  172. lbits &= fractMask;
  173. if ( binexp > 0 ){
  174. lbits |= fractHOB;
  175. } else {
  176. if ( lbits == 0L )
  177. throw new RuntimeException("Assertion botch: doubleToBigInt(0.0)");
  178. binexp +=1;
  179. while ( (lbits & fractHOB ) == 0L){
  180. lbits <<= 1;
  181. binexp -= 1;
  182. }
  183. }
  184. binexp -= expBias;
  185. int nbits = countBits( lbits );
  186. /*
  187. * We now know where the high-order 1 bit is,
  188. * and we know how many there are.
  189. */
  190. int lowOrderZeros = expShift+1-nbits;
  191. lbits >>>= lowOrderZeros;
  192. bigIntExp = binexp+1-nbits;
  193. bigIntNBits = nbits;
  194. return new FDBigInt( lbits );
  195. }
  196. /*
  197. * Compute a number that is the ULP of the given value,
  198. * for purposes of addition/subtraction. Generally easy.
  199. * More difficult if subtracting and the argument
  200. * is a normalized a power of 2, as the ULP changes at these points.
  201. */
  202. private static double
  203. ulp( double dval, boolean subtracting ){
  204. long lbits = Double.doubleToLongBits( dval ) & ~signMask;
  205. int binexp = (int)(lbits >>> expShift);
  206. double ulpval;
  207. if ( subtracting && ( binexp >= expShift ) && ((lbits&fractMask) == 0L) ){
  208. // for subtraction from normalized, powers of 2,
  209. // use next-smaller exponent
  210. binexp -= 1;
  211. }
  212. if ( binexp > expShift ){
  213. ulpval = Double.longBitsToDouble( ((long)(binexp-expShift))<<expShift );
  214. } else if ( binexp == 0 ){
  215. ulpval = Double.MIN_VALUE;
  216. } else {
  217. ulpval = Double.longBitsToDouble( 1L<<(binexp-1) );
  218. }
  219. if ( subtracting ) ulpval = - ulpval;
  220. return ulpval;
  221. }
  222. /*
  223. * Round a double to a float.
  224. * In addition to the fraction bits of the double,
  225. * look at the class instance variable roundDir,
  226. * which should help us avoid double-rounding error.
  227. * roundDir was set in hardValueOf if the estimate was
  228. * close enough, but not exact. It tells us which direction
  229. * of rounding is preferred.
  230. */
  231. float
  232. stickyRound( double dval ){
  233. long lbits = Double.doubleToLongBits( dval );
  234. long binexp = lbits & expMask;
  235. if ( binexp == 0L || binexp == expMask ){
  236. // what we have here is special.
  237. // don't worry, the right thing will happen.
  238. return (float) dval;
  239. }
  240. lbits += (long)roundDir; // hack-o-matic.
  241. return (float)Double.longBitsToDouble( lbits );
  242. }
  243. /*
  244. * This is the easy subcase --
  245. * all the significant bits, after scaling, are held in lvalue.
  246. * negSign and decExponent tell us what processing and scaling
  247. * has already been done. Exceptional cases have already been
  248. * stripped out.
  249. * In particular:
  250. * lvalue is a finite number (not Inf, nor NaN)
  251. * lvalue > 0L (not zero, nor negative).
  252. *
  253. * The only reason that we develop the digits here, rather than
  254. * calling on Long.toString() is that we can do it a little faster,
  255. * and besides want to treat trailing 0s specially. If Long.toString
  256. * changes, we should re-evaluate this strategy!
  257. */
  258. private void
  259. developLongDigits( int decExponent, long lvalue, long insignificant ){
  260. char digits[];
  261. int ndigits;
  262. int digitno;
  263. int c;
  264. //
  265. // Discard non-significant low-order bits, while rounding,
  266. // up to insignificant value.
  267. int i;
  268. for ( i = 0; insignificant >= 10L; i++ )
  269. insignificant /= 10L;
  270. if ( i != 0 ){
  271. long pow10 = long5pow[i] << i; // 10^i == 5^i * 2^i;
  272. long residue = lvalue % pow10;
  273. lvalue /= pow10;
  274. decExponent += i;
  275. if ( residue >= (pow10>>1) ){
  276. // round up based on the low-order bits we're discarding
  277. lvalue++;
  278. }
  279. }
  280. if ( lvalue <= Integer.MAX_VALUE ){
  281. if ( lvalue <= 0L )
  282. throw new RuntimeException("Assertion botch: value "+lvalue+" <= 0");
  283. // even easier subcase!
  284. // can do int arithmetic rather than long!
  285. int ivalue = (int)lvalue;
  286. digits = new char[ ndigits=10 ];
  287. digitno = ndigits-1;
  288. c = ivalue%10;
  289. ivalue /= 10;
  290. while ( c == 0 ){
  291. decExponent++;
  292. c = ivalue%10;
  293. ivalue /= 10;
  294. }
  295. while ( ivalue != 0){
  296. digits[digitno--] = (char)(c+'0');
  297. decExponent++;
  298. c = ivalue%10;
  299. ivalue /= 10;
  300. }
  301. digits[digitno] = (char)(c+'0');
  302. } else {
  303. // same algorithm as above (same bugs, too )
  304. // but using long arithmetic.
  305. digits = new char[ ndigits=20 ];
  306. digitno = ndigits-1;
  307. c = (int)(lvalue%10L);
  308. lvalue /= 10L;
  309. while ( c == 0 ){
  310. decExponent++;
  311. c = (int)(lvalue%10L);
  312. lvalue /= 10L;
  313. }
  314. while ( lvalue != 0L ){
  315. digits[digitno--] = (char)(c+'0');
  316. decExponent++;
  317. c = (int)(lvalue%10L);
  318. lvalue /= 10;
  319. }
  320. digits[digitno] = (char)(c+'0');
  321. }
  322. char result [];
  323. ndigits -= digitno;
  324. if ( digitno == 0 )
  325. result = digits;
  326. else {
  327. result = new char[ ndigits ];
  328. System.arraycopy( digits, digitno, result, 0, ndigits );
  329. }
  330. this.digits = result;
  331. this.decExponent = decExponent+1;
  332. this.nDigits = ndigits;
  333. }
  334. //
  335. // add one to the least significant digit.
  336. // in the unlikely event there is a carry out,
  337. // deal with it.
  338. // assert that this will only happen where there
  339. // is only one digit, e.g. (float)1e-44 seems to do it.
  340. //
  341. private void
  342. roundup(){
  343. int i;
  344. int q = digits[ i = (nDigits-1)];
  345. if ( q == '9' ){
  346. while ( q == '9' && i > 0 ){
  347. digits[i] = '0';
  348. q = digits[--i];
  349. }
  350. if ( q == '9' ){
  351. // carryout! High-order 1, rest 0s, larger exp.
  352. decExponent += 1;
  353. digits[0] = '1';
  354. return;
  355. }
  356. // else fall through.
  357. }
  358. digits[i] = (char)(q+1);
  359. }
  360. /*
  361. * FIRST IMPORTANT CONSTRUCTOR: DOUBLE
  362. */
  363. public FloatingDecimal( double d )
  364. {
  365. long dBits = Double.doubleToLongBits( d );
  366. long fractBits;
  367. int binExp;
  368. int nSignificantBits;
  369. // discover and delete sign
  370. if ( (dBits&signMask) != 0 ){
  371. isNegative = true;
  372. dBits ^= signMask;
  373. } else {
  374. isNegative = false;
  375. }
  376. // Begin to unpack
  377. // Discover obvious special cases of NaN and Infinity.
  378. binExp = (int)( (dBits&expMask) >> expShift );
  379. fractBits = dBits&fractMask;
  380. if ( binExp == (int)(expMask>>expShift) ) {
  381. isExceptional = true;
  382. if ( fractBits == 0L ){
  383. digits = infinity;
  384. } else {
  385. digits = notANumber;
  386. isNegative = false; // NaN has no sign!
  387. }
  388. nDigits = digits.length;
  389. return;
  390. }
  391. isExceptional = false;
  392. // Finish unpacking
  393. // Normalize denormalized numbers.
  394. // Insert assumed high-order bit for normalized numbers.
  395. // Subtract exponent bias.
  396. if ( binExp == 0 ){
  397. if ( fractBits == 0L ){
  398. // not a denorm, just a 0!
  399. decExponent = 0;
  400. digits = zero;
  401. nDigits = 1;
  402. return;
  403. }
  404. while ( (fractBits&fractHOB) == 0L ){
  405. fractBits <<= 1;
  406. binExp -= 1;
  407. }
  408. nSignificantBits = expShift + binExp +1; // recall binExp is - shift count.
  409. binExp += 1;
  410. } else {
  411. fractBits |= fractHOB;
  412. nSignificantBits = expShift+1;
  413. }
  414. binExp -= expBias;
  415. // call the routine that actually does all the hard work.
  416. dtoa( binExp, fractBits, nSignificantBits );
  417. }
  418. /*
  419. * SECOND IMPORTANT CONSTRUCTOR: SINGLE
  420. */
  421. public FloatingDecimal( float f )
  422. {
  423. int fBits = Float.floatToIntBits( f );
  424. int fractBits;
  425. int binExp;
  426. int nSignificantBits;
  427. // discover and delete sign
  428. if ( (fBits&singleSignMask) != 0 ){
  429. isNegative = true;
  430. fBits ^= singleSignMask;
  431. } else {
  432. isNegative = false;
  433. }
  434. // Begin to unpack
  435. // Discover obvious special cases of NaN and Infinity.
  436. binExp = (int)( (fBits&singleExpMask) >> singleExpShift );
  437. fractBits = fBits&singleFractMask;
  438. if ( binExp == (int)(singleExpMask>>singleExpShift) ) {
  439. isExceptional = true;
  440. if ( fractBits == 0L ){
  441. digits = infinity;
  442. } else {
  443. digits = notANumber;
  444. isNegative = false; // NaN has no sign!
  445. }
  446. nDigits = digits.length;
  447. return;
  448. }
  449. isExceptional = false;
  450. // Finish unpacking
  451. // Normalize denormalized numbers.
  452. // Insert assumed high-order bit for normalized numbers.
  453. // Subtract exponent bias.
  454. if ( binExp == 0 ){
  455. if ( fractBits == 0 ){
  456. // not a denorm, just a 0!
  457. decExponent = 0;
  458. digits = zero;
  459. nDigits = 1;
  460. return;
  461. }
  462. while ( (fractBits&singleFractHOB) == 0 ){
  463. fractBits <<= 1;
  464. binExp -= 1;
  465. }
  466. nSignificantBits = singleExpShift + binExp +1; // recall binExp is - shift count.
  467. binExp += 1;
  468. } else {
  469. fractBits |= singleFractHOB;
  470. nSignificantBits = singleExpShift+1;
  471. }
  472. binExp -= singleExpBias;
  473. // call the routine that actually does all the hard work.
  474. dtoa( binExp, ((long)fractBits)<<(expShift-singleExpShift), nSignificantBits );
  475. }
  476. private void
  477. dtoa( int binExp, long fractBits, int nSignificantBits )
  478. {
  479. int nFractBits; // number of significant bits of fractBits;
  480. int nTinyBits; // number of these to the right of the point.
  481. int decExp;
  482. // Examine number. Determine if it is an easy case,
  483. // which we can do pretty trivially using float/long conversion,
  484. // or whether we must do real work.
  485. nFractBits = countBits( fractBits );
  486. nTinyBits = Math.max( 0, nFractBits - binExp - 1 );
  487. if ( binExp <= maxSmallBinExp && binExp >= minSmallBinExp ){
  488. // Look more closely at the number to decide if,
  489. // with scaling by 10^nTinyBits, the result will fit in
  490. // a long.
  491. if ( (nTinyBits < long5pow.length) && ((nFractBits + n5bits[nTinyBits]) < 64 ) ){
  492. /*
  493. * We can do this:
  494. * take the fraction bits, which are normalized.
  495. * (a) nTinyBits == 0: Shift left or right appropriately
  496. * to align the binary point at the extreme right, i.e.
  497. * where a long int point is expected to be. The integer
  498. * result is easily converted to a string.
  499. * (b) nTinyBits > 0: Shift right by expShift-nFractBits,
  500. * which effectively converts to long and scales by
  501. * 2^nTinyBits. Then multiply by 5^nTinyBits to
  502. * complete the scaling. We know this won't overflow
  503. * because we just counted the number of bits necessary
  504. * in the result. The integer you get from this can
  505. * then be converted to a string pretty easily.
  506. */
  507. long halfULP;
  508. if ( nTinyBits == 0 ) {
  509. if ( binExp > nSignificantBits ){
  510. halfULP = 1L << ( binExp-nSignificantBits-1);
  511. } else {
  512. halfULP = 0L;
  513. }
  514. if ( binExp >= expShift ){
  515. fractBits <<= (binExp-expShift);
  516. } else {
  517. fractBits >>>= (expShift-binExp) ;
  518. }
  519. developLongDigits( 0, fractBits, halfULP );
  520. return;
  521. }
  522. /*
  523. * The following causes excess digits to be printed
  524. * out in the single-float case. Our manipulation of
  525. * halfULP here is apparently not correct. If we
  526. * better understand how this works, perhaps we can
  527. * use this special case again. But for the time being,
  528. * we do not.
  529. * else {
  530. * fractBits >>>= expShift+1-nFractBits;
  531. * fractBits *= long5pow[ nTinyBits ];
  532. * halfULP = long5pow[ nTinyBits ] >> (1+nSignificantBits-nFractBits);
  533. * developLongDigits( -nTinyBits, fractBits, halfULP );
  534. * return;
  535. * }
  536. */
  537. }
  538. }
  539. /*
  540. * This is the hard case. We are going to compute large positive
  541. * integers B and S and integer decExp, s.t.
  542. * d = ( B / S ) * 10^decExp
  543. * 1 <= B / S < 10
  544. * Obvious choices are:
  545. * decExp = floor( log10(d) )
  546. * B = d * 2^nTinyBits * 10^max( 0, -decExp )
  547. * S = 10^max( 0, decExp) * 2^nTinyBits
  548. * (noting that nTinyBits has already been forced to non-negative)
  549. * I am also going to compute a large positive integer
  550. * M = (1/2^nSignificantBits) * 2^nTinyBits * 10^max( 0, -decExp )
  551. * i.e. M is (1/2) of the ULP of d, scaled like B.
  552. * When we iterate through dividing B/S and picking off the
  553. * quotient bits, we will know when to stop when the remainder
  554. * is <= M.
  555. *
  556. * We keep track of powers of 2 and powers of 5.
  557. */
  558. /*
  559. * Estimate decimal exponent. (If it is small-ish,
  560. * we could double-check.)
  561. *
  562. * First, scale the mantissa bits such that 1 <= d2 < 2.
  563. * We are then going to estimate
  564. * log10(d2) ~=~ (d2-1.5)/1.5 + log(1.5)
  565. * and so we can estimate
  566. * log10(d) ~=~ log10(d2) + binExp * log10(2)
  567. * take the floor and call it decExp.
  568. * FIXME -- use more precise constants here. It costs no more.
  569. */
  570. double d2 = Double.longBitsToDouble(
  571. expOne | ( fractBits &~ fractHOB ) );
  572. decExp = (int)Math.floor(
  573. (d2-1.5D)*0.289529654D + 0.176091259 + (double)binExp * 0.301029995663981 );
  574. int B2, B5; // powers of 2 and powers of 5, respectively, in B
  575. int S2, S5; // powers of 2 and powers of 5, respectively, in S
  576. int M2, M5; // powers of 2 and powers of 5, respectively, in M
  577. int Bbits; // binary digits needed to represent B, approx.
  578. int tenSbits; // binary digits needed to represent 10*S, approx.
  579. FDBigInt Sval, Bval, Mval;
  580. B5 = Math.max( 0, -decExp );
  581. B2 = B5 + nTinyBits + binExp;
  582. S5 = Math.max( 0, decExp );
  583. S2 = S5 + nTinyBits;
  584. M5 = B5;
  585. M2 = B2 - nSignificantBits;
  586. /*
  587. * the long integer fractBits contains the (nFractBits) interesting
  588. * bits from the mantissa of d ( hidden 1 added if necessary) followed
  589. * by (expShift+1-nFractBits) zeros. In the interest of compactness,
  590. * I will shift out those zeros before turning fractBits into a
  591. * FDBigInt. The resulting whole number will be
  592. * d * 2^(nFractBits-1-binExp).
  593. */
  594. fractBits >>>= (expShift+1-nFractBits);
  595. B2 -= nFractBits-1;
  596. int common2factor = Math.min( B2, S2 );
  597. B2 -= common2factor;
  598. S2 -= common2factor;
  599. M2 -= common2factor;
  600. /*
  601. * HACK!! For exact powers of two, the next smallest number
  602. * is only half as far away as we think (because the meaning of
  603. * ULP changes at power-of-two bounds) for this reason, we
  604. * hack M2. Hope this works.
  605. */
  606. if ( nFractBits == 1 )
  607. M2 -= 1;
  608. if ( M2 < 0 ){
  609. // oops.
  610. // since we cannot scale M down far enough,
  611. // we must scale the other values up.
  612. B2 -= M2;
  613. S2 -= M2;
  614. M2 = 0;
  615. }
  616. /*
  617. * Construct, Scale, iterate.
  618. * Some day, we'll write a stopping test that takes
  619. * account of the assymetry of the spacing of floating-point
  620. * numbers below perfect powers of 2
  621. * 26 Sept 96 is not that day.
  622. * So we use a symmetric test.
  623. */
  624. char digits[] = this.digits = new char[18];
  625. int ndigit = 0;
  626. boolean low, high;
  627. long lowDigitDifference;
  628. int q;
  629. /*
  630. * Detect the special cases where all the numbers we are about
  631. * to compute will fit in int or long integers.
  632. * In these cases, we will avoid doing FDBigInt arithmetic.
  633. * We use the same algorithms, except that we "normalize"
  634. * our FDBigInts before iterating. This is to make division easier,
  635. * as it makes our fist guess (quotient of high-order words)
  636. * more accurate!
  637. *
  638. * Some day, we'll write a stopping test that takes
  639. * account of the assymetry of the spacing of floating-point
  640. * numbers below perfect powers of 2
  641. * 26 Sept 96 is not that day.
  642. * So we use a symmetric test.
  643. */
  644. Bbits = nFractBits + B2 + (( B5 < n5bits.length )? n5bits[B5] : ( B5*3 ));
  645. tenSbits = S2+1 + (( (S5+1) < n5bits.length )? n5bits[(S5+1)] : ( (S5+1)*3 ));
  646. if ( Bbits < 64 && tenSbits < 64){
  647. if ( Bbits < 32 && tenSbits < 32){
  648. // wa-hoo! They're all ints!
  649. int b = ((int)fractBits * small5pow[B5] ) << B2;
  650. int s = small5pow[S5] << S2;
  651. int m = small5pow[M5] << M2;
  652. int tens = s * 10;
  653. /*
  654. * Unroll the first iteration. If our decExp estimate
  655. * was too high, our first quotient will be zero. In this
  656. * case, we discard it and decrement decExp.
  657. */
  658. ndigit = 0;
  659. q = (int) ( b / s );
  660. b = 10 * ( b % s );
  661. m *= 10;
  662. low = (b < m );
  663. high = (b+m > tens );
  664. if ( q >= 10 ){
  665. // bummer, dude
  666. throw new RuntimeException( "Assertion botch: excessivly large digit "+q);
  667. } else if ( (q == 0) && ! high ){
  668. // oops. Usually ignore leading zero.
  669. decExp--;
  670. } else {
  671. digits[ndigit++] = (char)('0' + q);
  672. }
  673. /*
  674. * HACK! Java spec sez that we always have at least
  675. * one digit after the . in either F- or E-form output.
  676. * Thus we will need more than one digit if we're using
  677. * E-form
  678. */
  679. if ( decExp <= -3 || decExp >= 8 ){
  680. high = low = false;
  681. }
  682. while( ! low && ! high ){
  683. q = (int) ( b / s );
  684. b = 10 * ( b % s );
  685. m *= 10;
  686. if ( q >= 10 ){
  687. // bummer, dude
  688. throw new RuntimeException( "Assertion botch: excessivly large digit "+q);
  689. }
  690. if ( m > 0L ){
  691. low = (b < m );
  692. high = (b+m > tens );
  693. } else {
  694. // hack -- m might overflow!
  695. // in this case, it is certainly > b,
  696. // which won't
  697. // and b+m > tens, too, since that has overflowed
  698. // either!
  699. low = true;
  700. high = true;
  701. }
  702. digits[ndigit++] = (char)('0' + q);
  703. }
  704. lowDigitDifference = (b<<1) - tens;
  705. } else {
  706. // still good! they're all longs!
  707. long b = (fractBits * long5pow[B5] ) << B2;
  708. long s = long5pow[S5] << S2;
  709. long m = long5pow[M5] << M2;
  710. long tens = s * 10L;
  711. /*
  712. * Unroll the first iteration. If our decExp estimate
  713. * was too high, our first quotient will be zero. In this
  714. * case, we discard it and decrement decExp.
  715. */
  716. ndigit = 0;
  717. q = (int) ( b / s );
  718. b = 10L * ( b % s );
  719. m *= 10L;
  720. low = (b < m );
  721. high = (b+m > tens );
  722. if ( q >= 10 ){
  723. // bummer, dude
  724. throw new RuntimeException( "Assertion botch: excessivly large digit "+q);
  725. } else if ( (q == 0) && ! high ){
  726. // oops. Usually ignore leading zero.
  727. decExp--;
  728. } else {
  729. digits[ndigit++] = (char)('0' + q);
  730. }
  731. /*
  732. * HACK! Java spec sez that we always have at least
  733. * one digit after the . in either F- or E-form output.
  734. * Thus we will need more than one digit if we're using
  735. * E-form
  736. */
  737. if ( decExp <= -3 || decExp >= 8 ){
  738. high = low = false;
  739. }
  740. while( ! low && ! high ){
  741. q = (int) ( b / s );
  742. b = 10 * ( b % s );
  743. m *= 10;
  744. if ( q >= 10 ){
  745. // bummer, dude
  746. throw new RuntimeException( "Assertion botch: excessivly large digit "+q);
  747. }
  748. if ( m > 0L ){
  749. low = (b < m );
  750. high = (b+m > tens );
  751. } else {
  752. // hack -- m might overflow!
  753. // in this case, it is certainly > b,
  754. // which won't
  755. // and b+m > tens, too, since that has overflowed
  756. // either!
  757. low = true;
  758. high = true;
  759. }
  760. digits[ndigit++] = (char)('0' + q);
  761. }
  762. lowDigitDifference = (b<<1) - tens;
  763. }
  764. } else {
  765. FDBigInt tenSval;
  766. int shiftBias;
  767. /*
  768. * We really must do FDBigInt arithmetic.
  769. * Fist, construct our FDBigInt initial values.
  770. */
  771. Bval = multPow52( new FDBigInt( fractBits ), B5, B2 );
  772. Sval = constructPow52( S5, S2 );
  773. Mval = constructPow52( M5, M2 );
  774. // normalize so that division works better
  775. Bval.lshiftMe( shiftBias = Sval.normalizeMe() );
  776. Mval.lshiftMe( shiftBias );
  777. tenSval = Sval.mult( 10 );
  778. /*
  779. * Unroll the first iteration. If our decExp estimate
  780. * was too high, our first quotient will be zero. In this
  781. * case, we discard it and decrement decExp.
  782. */
  783. ndigit = 0;
  784. q = Bval.quoRemIteration( Sval );
  785. Mval = Mval.mult( 10 );
  786. low = (Bval.cmp( Mval ) < 0);
  787. high = (Bval.add( Mval ).cmp( tenSval ) > 0 );
  788. if ( q >= 10 ){
  789. // bummer, dude
  790. throw new RuntimeException( "Assertion botch: excessivly large digit "+q);
  791. } else if ( (q == 0) && ! high ){
  792. // oops. Usually ignore leading zero.
  793. decExp--;
  794. } else {
  795. digits[ndigit++] = (char)('0' + q);
  796. }
  797. /*
  798. * HACK! Java spec sez that we always have at least
  799. * one digit after the . in either F- or E-form output.
  800. * Thus we will need more than one digit if we're using
  801. * E-form
  802. */
  803. if ( decExp <= -3 || decExp >= 8 ){
  804. high = low = false;
  805. }
  806. while( ! low && ! high ){
  807. q = Bval.quoRemIteration( Sval );
  808. Mval = Mval.mult( 10 );
  809. if ( q >= 10 ){
  810. // bummer, dude
  811. throw new RuntimeException( "Assertion botch: excessivly large digit "+q);
  812. }
  813. low = (Bval.cmp( Mval ) < 0);
  814. high = (Bval.add( Mval ).cmp( tenSval ) > 0 );
  815. digits[ndigit++] = (char)('0' + q);
  816. }
  817. if ( high && low ){
  818. Bval.lshiftMe(1);
  819. lowDigitDifference = Bval.cmp(tenSval);
  820. } else
  821. lowDigitDifference = 0L; // this here only for flow analysis!
  822. }
  823. this.decExponent = decExp+1;
  824. this.digits = digits;
  825. this.nDigits = ndigit;
  826. /*
  827. * Last digit gets rounded based on stopping condition.
  828. */
  829. if ( high ){
  830. if ( low ){
  831. if ( lowDigitDifference == 0L ){
  832. // it's a tie!
  833. // choose based on which digits we like.
  834. if ( (digits[nDigits-1]&1) != 0 ) roundup();
  835. } else if ( lowDigitDifference > 0 ){
  836. roundup();
  837. }
  838. } else {
  839. roundup();
  840. }
  841. }
  842. }
  843. public String
  844. toString(){
  845. // most brain-dead version
  846. StringBuffer result = new StringBuffer( nDigits+8 );
  847. if ( isNegative ){ result.append( '-' ); }
  848. if ( isExceptional ){
  849. result.append( digits, 0, nDigits );
  850. } else {
  851. result.append( "0.");
  852. result.append( digits, 0, nDigits );
  853. result.append('e');
  854. result.append( decExponent );
  855. }
  856. return new String(result);
  857. }
  858. public String
  859. toJavaFormatString(){
  860. char result[] = new char[ nDigits + 10 ];
  861. int i = 0;
  862. if ( isNegative ){ result[0] = '-'; i = 1; }
  863. if ( isExceptional ){
  864. System.arraycopy( digits, 0, result, i, nDigits );
  865. i += nDigits;
  866. } else {
  867. if ( decExponent > 0 && decExponent < 8 ){
  868. // print digits.digits.
  869. int charLength = Math.min( nDigits, decExponent );
  870. System.arraycopy( digits, 0, result, i, charLength );
  871. i += charLength;
  872. if ( charLength < decExponent ){
  873. charLength = decExponent-charLength;
  874. System.arraycopy( zero, 0, result, i, charLength );
  875. i += charLength;
  876. result[i++] = '.';
  877. result[i++] = '0';
  878. } else {
  879. result[i++] = '.';
  880. if ( charLength < nDigits ){
  881. int t = nDigits - charLength;
  882. System.arraycopy( digits, charLength, result, i, t );
  883. i += t;
  884. } else{
  885. result[i++] = '0';
  886. }
  887. }
  888. } else if ( decExponent <=0 && decExponent > -3 ){
  889. result[i++] = '0';
  890. result[i++] = '.';
  891. if ( decExponent != 0 ){
  892. System.arraycopy( zero, 0, result, i, -decExponent );
  893. i -= decExponent;
  894. }
  895. System.arraycopy( digits, 0, result, i, nDigits );
  896. i += nDigits;
  897. } else {
  898. result[i++] = digits[0];
  899. result[i++] = '.';
  900. if ( nDigits > 1 ){
  901. System.arraycopy( digits, 1, result, i, nDigits-1 );
  902. i += nDigits-1;
  903. } else {
  904. result[i++] = '0';
  905. }
  906. result[i++] = 'E';
  907. int e;
  908. if ( decExponent <= 0 ){
  909. result[i++] = '-';
  910. e = -decExponent+1;
  911. } else {
  912. e = decExponent-1;
  913. }
  914. // decExponent has 1, 2, or 3, digits
  915. if ( e <= 9 ) {
  916. result[i++] = (char)( e+'0' );
  917. } else if ( e <= 99 ){
  918. result[i++] = (char)( e10 +'0' );
  919. result[i++] = (char)( e%10 + '0' );
  920. } else {
  921. result[i++] = (char)(e100+'0');
  922. e %= 100;
  923. result[i++] = (char)(e10+'0');
  924. result[i++] = (char)( e%10 + '0' );
  925. }
  926. }
  927. }
  928. return new String(result, 0, i);
  929. }
  930. public static FloatingDecimal
  931. readJavaFormatString( String in ) throws NumberFormatException {
  932. boolean isNegative = false;
  933. boolean signSeen = false;
  934. int decExp;
  935. char c;
  936. parseNumber:
  937. try{
  938. in = in.trim(); // don't fool around with white space.
  939. // throws NullPointerException if null
  940. int l = in.length();
  941. if ( l == 0 ) throw new NumberFormatException("empty String");
  942. int i = 0;
  943. switch ( c = in.charAt( i ) ){
  944. case '-':
  945. isNegative = true;
  946. //FALLTHROUGH
  947. case '+':
  948. i++;
  949. signSeen = true;
  950. }
  951. // Would handle NaN and Infinity here, but it isn't
  952. // part of the spec!
  953. //
  954. char[] digits = new char[ l ];
  955. int nDigits= 0;
  956. boolean decSeen = false;
  957. int decPt = 0;
  958. int nLeadZero = 0;
  959. int nTrailZero= 0;
  960. digitLoop:
  961. while ( i < l ){
  962. switch ( c = in.charAt( i ) ){
  963. case '0':
  964. if ( nDigits > 0 ){
  965. nTrailZero += 1;
  966. } else {
  967. nLeadZero += 1;
  968. }
  969. break; // out of switch.
  970. case '1':
  971. case '2':
  972. case '3':
  973. case '4':
  974. case '5':
  975. case '6':
  976. case '7':
  977. case '8':
  978. case '9':
  979. while ( nTrailZero > 0 ){
  980. digits[nDigits++] = '0';
  981. nTrailZero -= 1;
  982. }
  983. digits[nDigits++] = c;
  984. break; // out of switch.
  985. case '.':
  986. if ( decSeen ){
  987. // already saw one ., this is the 2nd.
  988. throw new NumberFormatException("multiple points");
  989. }
  990. decPt = i;
  991. if ( signSeen ){
  992. decPt -= 1;
  993. }
  994. decSeen = true;
  995. break; // out of switch.
  996. default:
  997. break digitLoop;
  998. }
  999. i++;
  1000. }
  1001. /*
  1002. * At this point, we've scanned all the digits and decimal
  1003. * point we're going to see. Trim off leading and trailing
  1004. * zeros, which will just confuse us later, and adjust
  1005. * our initial decimal exponent accordingly.
  1006. * To review:
  1007. * we have seen i total characters.
  1008. * nLeadZero of them were zeros before any other digits.
  1009. * nTrailZero of them were zeros after any other digits.
  1010. * if ( decSeen ), then a . was seen after decPt characters
  1011. * ( including leading zeros which have been discarded )
  1012. * nDigits characters were neither lead nor trailing
  1013. * zeros, nor point
  1014. */
  1015. /*
  1016. * special hack: if we saw no non-zero digits, then the
  1017. * answer is zero!
  1018. * Unfortunately, we feel honor-bound to keep parsing!
  1019. */
  1020. if ( nDigits == 0 ){
  1021. digits = zero;
  1022. nDigits = 1;
  1023. if ( nLeadZero == 0 ){
  1024. // we saw NO DIGITS AT ALL,
  1025. // not even a crummy 0!
  1026. // this is not allowed.
  1027. break parseNumber; // go throw exception
  1028. }
  1029. }
  1030. /* Our initial exponent is decPt, adjusted by the number of
  1031. * discarded zeros. Or, if there was no decPt,
  1032. * then its just nDigits adjusted by discarded trailing zeros.
  1033. */
  1034. if ( decSeen ){
  1035. decExp = decPt - nLeadZero;
  1036. } else {
  1037. decExp = nDigits+nTrailZero;
  1038. }
  1039. /*
  1040. * Look for 'e' or 'E' and an optionally signed integer.
  1041. */
  1042. if ( (i < l) && ((c = in.charAt(i) )=='e') || (c == 'E') ){
  1043. int expSign = 1;
  1044. int expVal = 0;
  1045. int reallyBig = Integer.MAX_VALUE / 10;
  1046. boolean expOverflow = false;
  1047. switch( in.charAt(++i) ){
  1048. case '-':
  1049. expSign = -1;
  1050. //FALLTHROUGH
  1051. case '+':
  1052. i++;
  1053. }
  1054. int expAt = i;
  1055. expLoop:
  1056. while ( i < l ){
  1057. if ( expVal >= reallyBig ){
  1058. // the next character will cause integer
  1059. // overflow.
  1060. expOverflow = true;
  1061. }
  1062. switch ( c = in.charAt(i++) ){
  1063. case '0':
  1064. case '1':
  1065. case '2':
  1066. case '3':
  1067. case '4':
  1068. case '5':
  1069. case '6':
  1070. case '7':
  1071. case '8':
  1072. case '9':
  1073. expVal = expVal*10 + ( (int)c - (int)'0' );
  1074. continue;
  1075. default:
  1076. i--; // back up.
  1077. break expLoop; // stop parsing exponent.
  1078. }
  1079. }
  1080. int expLimit = bigDecimalExponent+nDigits+nTrailZero;
  1081. if ( expOverflow || ( expVal > expLimit ) ){
  1082. //
  1083. // The intent here is to end up with
  1084. // infinity or zero, as appropriate.
  1085. // The reason for yielding such a small decExponent,
  1086. // rather than something intuitive such as
  1087. // expSign*Integer.MAX_VALUE, is that this value
  1088. // is subject to further manipulation in
  1089. // doubleValue() and floatValue(), and I don't want
  1090. // it to be able to cause overflow there!
  1091. // (The only way we can get into trouble here is for
  1092. // really outrageous nDigits+nTrailZero, such as 2 billion. )
  1093. //
  1094. decExp = expSign*expLimit;
  1095. } else {
  1096. // this should not overflow, since we tested
  1097. // for expVal > (MAX+N), where N >= abs(decExp)
  1098. decExp = decExp + expSign*expVal;
  1099. }
  1100. // if we saw something not a digit ( or end of string )
  1101. // after the [Ee][+-], without seeing any digits at all
  1102. // this is certainly an error. If we saw some digits,
  1103. // but then some trailing garbage, that might be ok.
  1104. // so we just fall through in that case.
  1105. // HUMBUG
  1106. if ( i == expAt )
  1107. break parseNumber; // certainly bad
  1108. }
  1109. /*
  1110. * We parsed everything we could.
  1111. * If there are leftovers, then this is not good input!
  1112. */
  1113. if ( i < l &&
  1114. ((i != l - 1) ||
  1115. (in.charAt(i) != 'f' &&
  1116. in.charAt(i) != 'F' &&
  1117. in.charAt(i) != 'd' &&
  1118. in.charAt(i) != 'D'))) {
  1119. break parseNumber; // go throw exception
  1120. }
  1121. return new FloatingDecimal( isNegative, decExp, digits, nDigits, false );
  1122. } catch ( StringIndexOutOfBoundsException e ){ }
  1123. throw new NumberFormatException( in );
  1124. }
  1125. /*
  1126. * Take a FloatingDecimal, which we presumably just scanned in,
  1127. * and find out what its value is, as a double.
  1128. *
  1129. * AS A SIDE EFFECT, SET roundDir TO INDICATE PREFERRED
  1130. * ROUNDING DIRECTION in case the result is really destined
  1131. * for a single-precision float.
  1132. */
  1133. public double
  1134. doubleValue(){
  1135. int kDigits = Math.min( nDigits, maxDecimalDigits+1 );
  1136. long lValue;
  1137. double dValue;
  1138. double rValue, tValue;
  1139. roundDir = 0;
  1140. /*
  1141. * convert the lead kDigits to a long integer.
  1142. */
  1143. // (special performance hack: start to do it using int)
  1144. int iValue = (int)digits[0]-(int)'0';
  1145. int iDigits = Math.min( kDigits, intDecimalDigits );
  1146. for ( int i=1; i < iDigits; i++ ){
  1147. iValue = iValue*10 + (int)digits[i]-(int)'0';
  1148. }
  1149. lValue = (long)iValue;
  1150. for ( int i=iDigits; i < kDigits; i++ ){
  1151. lValue = lValue*10L + (long)((int)digits[i]-(int)'0');
  1152. }
  1153. dValue = (double)lValue;
  1154. int exp = decExponent-kDigits;
  1155. /*
  1156. * lValue now contains a long integer with the value of
  1157. * the first kDigits digits of the number.
  1158. * dValue contains the (double) of the same.
  1159. */
  1160. if ( nDigits <= maxDecimalDigits ){
  1161. /*
  1162. * possibly an easy case.
  1163. * We know that the digits can be represented
  1164. * exactly. And if the exponent isn't too outrageous,
  1165. * the whole thing can be done with one operation,
  1166. * thus one rounding error.
  1167. */
  1168. if ( exp == 0 ) return (isNegative)? -dValue : dValue; // small floating integer
  1169. else if ( exp >= 0 ){
  1170. if ( exp <= maxSmallTen ){
  1171. /*
  1172. * Can get the answer with one operation,
  1173. * thus one roundoff.
  1174. */
  1175. rValue = dValue * small10pow[exp];
  1176. if ( mustSetRoundDir ){
  1177. tValue = rValue / small10pow[exp];
  1178. roundDir = ( tValue == dValue ) ? 0
  1179. :( tValue < dValue ) ? 1
  1180. : -1;
  1181. }
  1182. return (isNegative)? -rValue : rValue;
  1183. }
  1184. int slop = maxDecimalDigits - kDigits;
  1185. if ( exp <= maxSmallTen+slop ){
  1186. /*
  1187. * We can multiply dValue by 10^(slop)
  1188. * and it is still "small" and exact.
  1189. * Then we can multiply by 10^(exp-slop)
  1190. * with one rounding.
  1191. */
  1192. dValue *= small10pow[slop];
  1193. rValue = dValue * small10pow[exp-slop];
  1194. if ( mustSetRoundDir ){
  1195. tValue = rValue / small10pow[exp-slop];
  1196. roundDir = ( tValue == dValue ) ? 0
  1197. :( tValue < dValue ) ? 1
  1198. : -1;
  1199. }
  1200. return (isNegative)? -rValue : rValue;
  1201. }
  1202. /*
  1203. * Else we have a hard case with a positive exp.
  1204. */
  1205. } else {
  1206. if ( exp >= -maxSmallTen ){
  1207. /*
  1208. * Can get the answer in one division.
  1209. */
  1210. rValue = dValue / small10pow[-exp];
  1211. tValue = rValue * small10pow[-exp];
  1212. if ( mustSetRoundDir ){
  1213. roundDir = ( tValue == dValue ) ? 0
  1214. :( tValue < dValue ) ? 1
  1215. : -1;
  1216. }
  1217. return (isNegative)? -rValue : rValue;
  1218. }
  1219. /*
  1220. * Else we have a hard case with a negative exp.
  1221. */
  1222. }
  1223. }
  1224. /*
  1225. * Harder cases:
  1226. * The sum of digits plus exponent is greater than
  1227. * what we think we can do with one error.
  1228. *
  1229. * Start by approximating the right answer by,
  1230. * naively, scaling by powers of 10.
  1231. */
  1232. if ( exp > 0 ){
  1233. if ( decExponent > maxDecimalExponent+1 ){
  1234. /*
  1235. * Lets face it. This is going to be
  1236. * Infinity. Cut to the chase.
  1237. */
  1238. return (isNegative)? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
  1239. }
  1240. if ( (exp&15) != 0 ){
  1241. dValue *= small10pow[exp&15];
  1242. }
  1243. if ( (exp>>=4) != 0 ){
  1244. int j;
  1245. for( j = 0; exp > 1; j++, exp>>=1 ){
  1246. if ( (exp&1)!=0)
  1247. dValue *= big10pow[j];
  1248. }
  1249. /*
  1250. * The reason for the weird exp > 1 condition
  1251. * in the above loop was so that the last multiply
  1252. * would get unrolled. We handle it here.
  1253. * It could overflow.
  1254. */
  1255. double t = dValue * big10pow[j];
  1256. if ( Double.isInfinite( t ) ){
  1257. /*
  1258. * It did overflow.
  1259. * Look more closely at the result.
  1260. * If the exponent is just one too large,
  1261. * then use the maximum finite as our estimate
  1262. * value. Else call the result infinity
  1263. * and punt it.
  1264. * ( I presume this could happen because
  1265. * rounding forces the result here to be
  1266. * an ULP or two larger than
  1267. * Double.MAX_VALUE ).
  1268. */
  1269. t = dValue / 2.0;
  1270. t *= big10pow[j];
  1271. if ( Double.isInfinite( t ) ){
  1272. return (isNegative)? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
  1273. }
  1274. t = Double.MAX_VALUE;
  1275. }
  1276. dValue = t;
  1277. }
  1278. } else if ( exp < 0 ){
  1279. exp = -exp;
  1280. if ( decExponent < minDecimalExponent-1 ){
  1281. /*
  1282. * Lets face it. This is going to be
  1283. * zero. Cut to the chase.
  1284. */
  1285. return (isNegative)? -0.0 : 0.0;
  1286. }
  1287. if ( (exp&15) != 0 ){
  1288. dValue /= small10pow[exp&15];
  1289. }
  1290. if ( (exp>>=4) != 0 ){
  1291. int j;
  1292. for( j = 0; exp > 1; j++, exp>>=1 ){
  1293. if ( (exp&1)!=0)
  1294. dValue *= tiny10pow[j];
  1295. }
  1296. /*
  1297. * The reason for the weird exp > 1 condition
  1298. * in the above loop was so that the last multiply
  1299. * would get unrolled. We handle it here.
  1300. * It could underflow.
  1301. */
  1302. double t = dValue * tiny10pow[j];
  1303. if ( t == 0.0 ){
  1304. /*
  1305. * It did underflow.
  1306. * Look more closely at the result.
  1307. * If the exponent is just one too small,
  1308. * then use the minimum finite as our estimate
  1309. * value. Else call the result 0.0
  1310. * and punt it.
  1311. * ( I presume this could happen because
  1312. * rounding forces the result here to be
  1313. * an ULP or two less than
  1314. * Double.MIN_VALUE ).
  1315. */
  1316. t = dValue * 2.0;
  1317. t *= tiny10pow[j];
  1318. if ( t == 0.0 ){
  1319. return (isNegative)? -0.0 : 0.0;
  1320. }
  1321. t = Double.MIN_VALUE;
  1322. }
  1323. dValue = t;
  1324. }
  1325. }
  1326. /*
  1327. * dValue is now approximately the result.
  1328. * The hard part is adjusting it, by comparison
  1329. * with FDBigInt arithmetic.
  1330. * Formulate the EXACT big-number result as
  1331. * bigD0 * 10^exp
  1332. */
  1333. FDBigInt bigD0 = new FDBigInt( lValue, digits, kDigits, nDigits );
  1334. exp = decExponent - nDigits;
  1335. correctionLoop:
  1336. while(true){
  1337. /* AS A SIDE EFFECT, THIS METHOD WILL SET THE INSTANCE VARIABLES
  1338. * bigIntExp and bigIntNBits
  1339. */
  1340. FDBigInt bigB = doubleToBigInt( dValue );
  1341. /*
  1342. * Scale bigD, bigB appropriately for
  1343. * big-integer operations.
  1344. * Naively, we multipy by powers of ten
  1345. * and powers of two. What we actually do
  1346. * is keep track of the powers of 5 and
  1347. * powers of 2 we would use, then factor out
  1348. * common divisors before doing the work.
  1349. */
  1350. int B2, B5; // powers of 2, 5 in bigB
  1351. int D2, D5; // powers of 2, 5 in bigD
  1352. int Ulp2; // powers of 2 in halfUlp.
  1353. if ( exp >= 0 ){
  1354. B2 = B5 = 0;
  1355. D2 = D5 = exp;
  1356. } else {
  1357. B2 = B5 = -exp;
  1358. D2 = D5 = 0;
  1359. }
  1360. if ( bigIntExp >= 0 ){
  1361. B2 += bigIntExp;
  1362. } else {
  1363. D2 -= bigIntExp;
  1364. }
  1365. Ulp2 = B2;
  1366. // shift bigB and bigD left by a number s. t.
  1367. // halfUlp is still an integer.
  1368. int hulpbias;
  1369. if ( bigIntExp+bigIntNBits <= -expBias+1 ){
  1370. // This is going to be a denormalized number
  1371. // (if not actually zero).
  1372. // half an ULP is at 2^-(expBias+expShift+1)
  1373. hulpbias = bigIntExp+ expBias + expShift;
  1374. } else {
  1375. hulpbias = expShift + 2 - bigIntNBits;
  1376. }
  1377. B2 += hulpbias;
  1378. D2 += hulpbias;
  1379. // if there are common factors of 2, we might just as well
  1380. // factor them out, as they add nothing useful.
  1381. int common2 = Math.min( B2, Math.min( D2, Ulp2 ) );
  1382. B2 -= common2;
  1383. D2 -= common2;
  1384. Ulp2 -= common2;
  1385. // do multiplications by powers of 5 and 2
  1386. bigB = multPow52( bigB, B5, B2 );
  1387. FDBigInt bigD = multPow52( new FDBigInt( bigD0 ), D5, D2 );
  1388. //
  1389. // to recap:
  1390. // bigB is the scaled-big-int version of our floating-point
  1391. // candidate.
  1392. // bigD is the scaled-big-int version of the exact value
  1393. // as we understand it.
  1394. // halfUlp is 1/2 an ulp of bigB, except for special cases
  1395. // of exact powers of 2
  1396. //
  1397. // the plan is to compare bigB with bigD, and if the difference
  1398. // is less than halfUlp, then we're satisfied. Otherwise,
  1399. // use the ratio of difference to halfUlp to calculate a fudge
  1400. // factor to add to the floating value, then go 'round again.
  1401. //
  1402. FDBigInt diff;
  1403. int cmpResult;
  1404. boolean overvalue;
  1405. if ( (cmpResult = bigB.cmp( bigD ) ) > 0 ){
  1406. overvalue = true; // our candidate is too big.
  1407. diff = bigB.sub( bigD );
  1408. if ( (bigIntNBits == 1) && (bigIntExp > -expBias) ){
  1409. // candidate is a normalized exact power of 2 and
  1410. // is too big. We will be subtracting.
  1411. // For our purposes, ulp is the ulp of the
  1412. // next smaller range.
  1413. Ulp2 -= 1;
  1414. if ( Ulp2 < 0 ){
  1415. // rats. Cannot de-scale ulp this far.
  1416. // must scale diff in other direction.
  1417. Ulp2 = 0;
  1418. diff.lshiftMe( 1 );
  1419. }
  1420. }
  1421. } else if ( cmpResult < 0 ){
  1422. overvalue = false; // our candidate is too small.
  1423. diff = bigD.sub( bigB );
  1424. } else {
  1425. // the candidate is exactly right!
  1426. // this happens with surprising fequency
  1427. break correctionLoop;
  1428. }
  1429. FDBigInt halfUlp = constructPow52( B5, Ulp2 );
  1430. if ( (cmpResult = diff.cmp( halfUlp ) ) < 0 ){
  1431. // difference is small.
  1432. // this is close enough
  1433. roundDir = overvalue ? -1 : 1;
  1434. break correctionLoop;
  1435. } else if ( cmpResult == 0 ){
  1436. // difference is exactly half an ULP
  1437. // round to some other value maybe, then finish
  1438. dValue += 0.5*ulp( dValue, overvalue );
  1439. // should check for bigIntNBits == 1 here??
  1440. roundDir = overvalue ? -1 : 1;
  1441. break correctionLoop;
  1442. } else {
  1443. // difference is non-trivial.
  1444. // could scale addend by ratio of difference to
  1445. // halfUlp here, if we bothered to compute that difference.
  1446. // Most of the time ( I hope ) it is about 1 anyway.
  1447. dValue += ulp( dValue, overvalue );
  1448. if ( dValue == 0.0 || dValue == Double.POSITIVE_INFINITY )
  1449. break correctionLoop; // oops. Fell off end of range.
  1450. continue; // try again.
  1451. }
  1452. }
  1453. return (isNegative)? -dValue : dValue;
  1454. }
  1455. /*
  1456. * Take a FloatingDecimal, which we presumably just scanned in,
  1457. * and find out what its value is, as a float.
  1458. * This is distinct from doubleValue() to avoid the extremely
  1459. * unlikely case of a double rounding error, wherein the converstion
  1460. * to double has one rounding error, and the conversion of that double
  1461. * to a float has another rounding error, IN THE WRONG DIRECTION,
  1462. * ( because of the preference to a zero low-order bit ).
  1463. */
  1464. public float
  1465. floatValue(){
  1466. int kDigits = Math.min( nDigits, singleMaxDecimalDigits+1 );
  1467. int iValue;
  1468. float fValue;
  1469. /*
  1470. * convert the lead kDigits to an integer.
  1471. */
  1472. iValue = (int)digits[0]-(int)'0';
  1473. for ( int i=1; i < kDigits; i++ ){
  1474. iValue = iValue*10 + (int)digits[i]-(int)'0';
  1475. }
  1476. fValue = (float)iValue;
  1477. int exp = decExponent-kDigits;
  1478. /*
  1479. * iValue now contains an integer with the value of
  1480. * the first kDigits digits of the number.
  1481. * fValue contains the (float) of the same.
  1482. */
  1483. if ( nDigits <= singleMaxDecimalDigits ){
  1484. /*
  1485. * possibly an easy case.
  1486. * We know that the digits can be represented
  1487. * exactly. And if the exponent isn't too outrageous,
  1488. * the whole thing can be done with one operation,
  1489. * thus one rounding error.
  1490. */
  1491. if ( exp == 0 ) return (isNegative)? -fValue : fValue; // small floating integer
  1492. else if ( exp >= 0 ){
  1493. if ( exp <= singleMaxSmallTen ){
  1494. /*
  1495. * Can get the answer with one operation,
  1496. * thus one roundoff.
  1497. */
  1498. fValue *= singleSmall10pow[exp];
  1499. return (isNegative)? -fValue : fValue;
  1500. }
  1501. int slop = singleMaxDecimalDigits - kDigits;
  1502. if ( exp <= singleMaxSmallTen+slop ){
  1503. /*
  1504. * We can multiply dValue by 10^(slop)
  1505. * and it is still "small" and exact.
  1506. * Then we can multiply by 10^(exp-slop)
  1507. * with one rounding.
  1508. */
  1509. fValue *= singleSmall10pow[slop];
  1510. fValue *= singleSmall10pow[exp-slop];
  1511. return (isNegative)? -fValue : fValue;
  1512. }
  1513. /*
  1514. * Else we have a hard case with a positive exp.
  1515. */
  1516. } else {
  1517. if ( exp >= -singleMaxSmallTen ){
  1518. /*
  1519. * Can get the answer in one division.
  1520. */
  1521. fValue /= singleSmall10pow[-exp];
  1522. return (isNegative)? -fValue : fValue;
  1523. }
  1524. /*
  1525. * Else we have a hard case with a negative exp.
  1526. */
  1527. }
  1528. } else if ( (decExponent >= nDigits) && (nDigits+decExponent <= maxDecimalDigits) ){
  1529. /*
  1530. * In double-precision, this is an exact floating integer.
  1531. * So we can compute to double, then shorten to float
  1532. * with one round, and get the right answer.
  1533. *
  1534. * First, finish accumulating digits.
  1535. * Then convert that integer to a double, multiply
  1536. * by the appropriate power of ten, and convert to float.
  1537. */
  1538. long lValue = (long)iValue;
  1539. for ( int i=kDigits; i < nDigits; i++ ){
  1540. lValue = lValue*10L + (long)((int)digits[i]-(int)'0');
  1541. }
  1542. double dValue = (double)lValue;
  1543. exp = decExponent-nDigits;
  1544. dValue *= small10pow[exp];
  1545. fValue = (float)dValue;
  1546. return (isNegative)? -fValue : fValue;
  1547. }
  1548. /*
  1549. * Harder cases:
  1550. * The sum of digits plus exponent is greater than
  1551. * what we think we can do with one error.
  1552. *
  1553. * Start by weeding out obviously out-of-range
  1554. * results, then convert to double and go to
  1555. * common hard-case code.
  1556. */
  1557. if ( decExponent > singleMaxDecimalExponent+1 ){
  1558. /*
  1559. * Lets face it. This is going to be
  1560. * Infinity. Cut to the chase.
  1561. */
  1562. return (isNegative)? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
  1563. } else if ( decExponent < singleMinDecimalExponent-1 ){
  1564. /*
  1565. * Lets face it. This is going to be
  1566. * zero. Cut to the chase.
  1567. */
  1568. return (isNegative)? -0.0f : 0.0f;
  1569. }
  1570. /*
  1571. * Here, we do 'way too much work, but throwing away
  1572. * our partial results, and going and doing the whole
  1573. * thing as double, then throwing away half the bits that computes
  1574. * when we convert back to float.
  1575. *
  1576. * The alternative is to reproduce the whole multiple-precision
  1577. * algorythm for float precision, or to try to parameterize it
  1578. * for common usage. The former will take about 400 lines of code,
  1579. * and the latter I tried without success. Thus the semi-hack
  1580. * answer here.
  1581. */
  1582. mustSetRoundDir = true;
  1583. double dValue = doubleValue();
  1584. return stickyRound( dValue );
  1585. }
  1586. /*
  1587. * All the positive powers of 10 that can be
  1588. * represented exactly in double/float.
  1589. */
  1590. private static final double small10pow[] = {
  1591. 1.0e0,
  1592. 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,
  1593. 1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10,
  1594. 1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15,
  1595. 1.0e16, 1.0e17, 1.0e18, 1.0e19, 1.0e20,
  1596. 1.0e21, 1.0e22
  1597. };
  1598. private static final float singleSmall10pow[] = {
  1599. 1.0e0f,
  1600. 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
  1601. 1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
  1602. };
  1603. private static final double big10pow[] = {
  1604. 1e16, 1e32, 1e64, 1e128, 1e256 };
  1605. private static final double tiny10pow[] = {
  1606. 1e-16, 1e-32, 1e-64, 1e-128, 1e-256 };
  1607. private static final int maxSmallTen = small10pow.length-1;
  1608. private static final int singleMaxSmallTen = singleSmall10pow.length-1;
  1609. private static final int small5pow[] = {
  1610. 1,
  1611. 5,
  1612. 5*5,
  1613. 5*5*5,
  1614. 5*5*5*5,
  1615. 5*5*5*5*5,
  1616. 5*5*5*5*5*5,
  1617. 5*5*5*5*5*5*5,
  1618. 5*5*5*5*5*5*5*5,
  1619. 5*5*5*5*5*5*5*5*5,
  1620. 5*5*5*5*5*5*5*5*5*5,
  1621. 5*5*5*5*5*5*5*5*5*5*5,
  1622. 5*5*5*5*5*5*5*5*5*5*5*5,
  1623. 5*5*5*5*5*5*5*5*5*5*5*5*5
  1624. };
  1625. private static final long long5pow[] = {
  1626. 1L,
  1627. 5L,
  1628. 5L*5,
  1629. 5L*5*5,
  1630. 5L*5*5*5,
  1631. 5L*5*5*5*5,
  1632. 5L*5*5*5*5*5,
  1633. 5L*5*5*5*5*5*5,
  1634. 5L*5*5*5*5*5*5*5,
  1635. 5L*5*5*5*5*5*5*5*5,
  1636. 5L*5*5*5*5*5*5*5*5*5,
  1637. 5L*5*5*5*5*5*5*5*5*5*5,
  1638. 5L*5*5*5*5*5*5*5*5*5*5*5,
  1639. 5L*5*5*5*5*5*5*5*5*5*5*5*5,
  1640. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1641. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1642. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1643. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1644. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1645. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1646. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1647. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1648. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1649. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1650. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1651. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1652. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1653. };
  1654. // approximately ceil( log2( long5pow[i] ) )
  1655. private static final int n5bits[] = {
  1656. 0,
  1657. 3,
  1658. 5,
  1659. 7,
  1660. 10,
  1661. 12,
  1662. 14,
  1663. 17,
  1664. 19,
  1665. 21,
  1666. 24,
  1667. 26,
  1668. 28,
  1669. 31,
  1670. 33,
  1671. 35,
  1672. 38,
  1673. 40,
  1674. 42,
  1675. 45,
  1676. 47,
  1677. 49,
  1678. 52,
  1679. 54,
  1680. 56,
  1681. 59,
  1682. 61,
  1683. };
  1684. private static final char infinity[] = { 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y' };
  1685. private static final char notANumber[] = { 'N', 'a', 'N' };
  1686. private static final char zero[] = { '0', '0', '0', '0', '0', '0', '0', '0' };
  1687. }
  1688. /*
  1689. * A really, really simple bigint package
  1690. * tailored to the needs of floating base conversion.
  1691. */
  1692. class FDBigInt {
  1693. int nWords; // number of words used
  1694. int data[]; // value: data[0] is least significant
  1695. public FDBigInt( int v ){
  1696. nWords = 1;
  1697. data = new int[1];
  1698. data[0] = v;
  1699. }
  1700. public FDBigInt( long v ){
  1701. data = new int[2];
  1702. data[0] = (int)v;
  1703. data[1] = (int)(v>>>32);
  1704. nWords = (data[1]==0) ? 1 : 2;
  1705. }
  1706. public FDBigInt( FDBigInt other ){
  1707. data = new int[nWords = other.nWords];
  1708. System.arraycopy( other.data, 0, data, 0, nWords );
  1709. }
  1710. private FDBigInt( int [] d, int n ){
  1711. data = d;
  1712. nWords = n;
  1713. }
  1714. public FDBigInt( long seed, char digit[], int nd0, int nd ){
  1715. int n= (nd+8)/9; // estimate size needed.
  1716. if ( n < 2 ) n = 2;
  1717. data = new int[n]; // allocate enough space
  1718. data[0] = (int)seed; // starting value
  1719. data[1] = (int)(seed>>>32);
  1720. nWords = (data[1]==0) ? 1 : 2;
  1721. int i = nd0;
  1722. int limit = nd-5; // slurp digits 5 at a time.
  1723. int v;
  1724. while ( i < limit ){
  1725. int ilim = i+5;
  1726. v = (int)digit[i++]-(int)'0';
  1727. while( i <ilim ){
  1728. v = 10*v + (int)digit[i++]-(int)'0';
  1729. }
  1730. multaddMe( 100000, v); // ... where 100000 is 10^5.
  1731. }
  1732. int factor = 1;
  1733. v = 0;
  1734. while ( i < nd ){
  1735. v = 10*v + (int)digit[i++]-(int)'0';
  1736. factor *= 10;
  1737. }
  1738. if ( factor != 1 ){
  1739. multaddMe( factor, v );
  1740. }
  1741. }
  1742. /*
  1743. * Left shift by c bits.
  1744. * Shifts this in place.
  1745. */
  1746. public void
  1747. lshiftMe( int c )throws IllegalArgumentException {
  1748. if ( c <= 0 ){
  1749. if ( c == 0 )
  1750. return; // silly.
  1751. else
  1752. throw new IllegalArgumentException("negative shift count");
  1753. }
  1754. int wordcount = c>>5;
  1755. int bitcount = c & 0x1f;
  1756. int anticount = 32-bitcount;
  1757. int t[] = data;
  1758. int s[] = data;
  1759. if ( nWords+wordcount+1 > t.length ){
  1760. // reallocate.
  1761. t = new int[ nWords+wordcount+1 ];
  1762. }
  1763. int target = nWords+wordcount;
  1764. int src = nWords-1;
  1765. if ( bitcount == 0 ){
  1766. // special hack, since an anticount of 32 won't go!
  1767. System.arraycopy( s, 0, t, wordcount, nWords );
  1768. target = wordcount-1;
  1769. } else {
  1770. t[target--] = s[src]>>>anticount;
  1771. while ( src >= 1 ){
  1772. t[target--] = (s[src]<<bitcount) | (s[--src]>>>anticount);
  1773. }
  1774. t[target--] = s[src]<<bitcount;
  1775. }
  1776. while( target >= 0 ){
  1777. t[target--] = 0;
  1778. }
  1779. data = t;
  1780. nWords += wordcount + 1;
  1781. // may have constructed high-order word of 0.
  1782. // if so, trim it
  1783. while ( nWords > 1 && data[nWords-1] == 0 )
  1784. nWords--;
  1785. }
  1786. /*
  1787. * normalize this number by shifting until
  1788. * the MSB of the number is at 0x08000000.
  1789. * This is in preparation for quoRemIteration, below.
  1790. * The idea is that, to make division easier, we want the
  1791. * divisor to be "normalized" -- usually this means shifting
  1792. * the MSB into the high words sign bit. But because we know that
  1793. * the quotient will be 0 < q < 10, we would like to arrange that
  1794. * the dividend not span up into another word of precision.
  1795. * (This needs to be explained more clearly!)
  1796. */
  1797. public int
  1798. normalizeMe() throws IllegalArgumentException {
  1799. int src;
  1800. int wordcount = 0;
  1801. int bitcount = 0;
  1802. int v = 0;
  1803. for ( src= nWords-1 ; src >= 0 && (v=data[src]) == 0 ; src--){
  1804. wordcount += 1;
  1805. }
  1806. if ( src < 0 ){
  1807. // oops. Value is zero. Cannot normalize it!
  1808. throw new IllegalArgumentException("zero value");
  1809. }
  1810. /*
  1811. * In most cases, we assume that wordcount is zero. This only
  1812. * makes sense, as we try not to maintain any high-order
  1813. * words full of zeros. In fact, if there are zeros, we will
  1814. * simply SHORTEN our number at this point. Watch closely...
  1815. */
  1816. nWords -= wordcount;
  1817. /*
  1818. * Compute how far left we have to shift v s.t. its highest-
  1819. * order bit is in the right place. Then call lshiftMe to
  1820. * do the work.
  1821. */
  1822. if ( (v & 0xf0000000) != 0 ){
  1823. // will have to shift up into the next word.
  1824. // too bad.
  1825. for( bitcount = 32 ; (v & 0xf0000000) != 0 ; bitcount-- )
  1826. v >>>= 1;
  1827. } else {
  1828. while ( v <= 0x000fffff ){
  1829. // hack: byte-at-a-time shifting
  1830. v <<= 8;
  1831. bitcount += 8;
  1832. }
  1833. while ( v <= 0x07ffffff ){
  1834. v <<= 1;
  1835. bitcount += 1;
  1836. }
  1837. }
  1838. if ( bitcount != 0 )
  1839. lshiftMe( bitcount );
  1840. return bitcount;
  1841. }
  1842. /*
  1843. * Multiply a FDBigInt by an int.
  1844. * Result is a new FDBigInt.
  1845. */
  1846. public FDBigInt
  1847. mult( int iv ) {
  1848. long v = iv;
  1849. int r[];
  1850. long p;
  1851. // guess adequate size of r.
  1852. r = new int[ ( v * ((long)data[nWords-1]&0xffffffffL) > 0xfffffffL ) ? nWords+1 : nWords ];
  1853. p = 0L;
  1854. for( int i=0; i < nWords; i++ ) {
  1855. p += v * ((long)data[i]&0xffffffffL);
  1856. r[i] = (int)p;
  1857. p >>>= 32;
  1858. }
  1859. if ( p == 0L){
  1860. return new FDBigInt( r, nWords );
  1861. } else {
  1862. r[nWords] = (int)p;
  1863. return new FDBigInt( r, nWords+1 );
  1864. }
  1865. }
  1866. /*
  1867. * Multiply a FDBigInt by an int and add another int.
  1868. * Result is computed in place.
  1869. * Hope it fits!
  1870. */
  1871. public void
  1872. multaddMe( int iv, int addend ) {
  1873. long v = iv;
  1874. long p;
  1875. // unroll 0th iteration, doing addition.
  1876. p = v * ((long)data[0]&0xffffffffL) + ((long)addend&0xffffffffL);
  1877. data[0] = (int)p;
  1878. p >>>= 32;
  1879. for( int i=1; i < nWords; i++ ) {
  1880. p += v * ((long)data[i]&0xffffffffL);
  1881. data[i] = (int)p;
  1882. p >>>= 32;
  1883. }
  1884. if ( p != 0L){
  1885. data[nWords] = (int)p; // will fail noisily if illegal!
  1886. nWords++;
  1887. }
  1888. }
  1889. /*
  1890. * Multiply a FDBigInt by another FDBigInt.
  1891. * Result is a new FDBigInt.
  1892. */
  1893. public FDBigInt
  1894. mult( FDBigInt other ){
  1895. // crudely guess adequate size for r
  1896. int r[] = new int[ nWords + other.nWords ];
  1897. int i;
  1898. // I think I am promised zeros...
  1899. for( i = 0; i < this.nWords; i++ ){
  1900. long v = (long)this.data[i] & 0xffffffffL; // UNSIGNED CONVERSION
  1901. long p = 0L;
  1902. int j;
  1903. for( j = 0; j < other.nWords; j++ ){
  1904. p += ((long)r[i+j]&0xffffffffL) + v*((long)other.data[j]&0xffffffffL); // UNSIGNED CONVERSIONS ALL 'ROUND.
  1905. r[i+j] = (int)p;
  1906. p >>>= 32;
  1907. }
  1908. r[i+j] = (int)p;
  1909. }
  1910. // compute how much of r we actually needed for all that.
  1911. for ( i = r.length-1; i> 0; i--)
  1912. if ( r[i] != 0 )
  1913. break;
  1914. return new FDBigInt( r, i+1 );
  1915. }
  1916. /*
  1917. * Add one FDBigInt to another. Return a FDBigInt
  1918. */
  1919. public FDBigInt
  1920. add( FDBigInt other ){
  1921. int i;
  1922. int a[], b[];
  1923. int n, m;
  1924. long c = 0L;
  1925. // arrange such that a.nWords >= b.nWords;
  1926. // n = a.nWords, m = b.nWords
  1927. if ( this.nWords >= other.nWords ){
  1928. a = this.data;
  1929. n = this.nWords;
  1930. b = other.data;
  1931. m = other.nWords;
  1932. } else {
  1933. a = other.data;
  1934. n = other.nWords;
  1935. b = this.data;
  1936. m = this.nWords;
  1937. }
  1938. int r[] = new int[ n ];
  1939. for ( i = 0; i < n; i++ ){
  1940. c += (long)a[i] & 0xffffffffL;
  1941. if ( i < m ){
  1942. c += (long)b[i] & 0xffffffffL;
  1943. }
  1944. r[i] = (int) c;
  1945. c >>= 32; // signed shift.
  1946. }
  1947. if ( c != 0L ){
  1948. // oops -- carry out -- need longer result.
  1949. int s[] = new int[ r.length+1 ];
  1950. System.arraycopy( r, 0, s, 0, r.length );
  1951. s[i++] = (int)c;
  1952. return new FDBigInt( s, i );
  1953. }
  1954. return new FDBigInt( r, i );
  1955. }
  1956. /*
  1957. * Subtract one FDBigInt from another. Return a FDBigInt
  1958. * Assert that the result is positive.
  1959. */
  1960. public FDBigInt
  1961. sub( FDBigInt other ){
  1962. int r[] = new int[ this.nWords ];
  1963. int i;
  1964. int n = this.nWords;
  1965. int m = other.nWords;
  1966. int nzeros = 0;
  1967. long c = 0L;
  1968. for ( i = 0; i < n; i++ ){
  1969. c += (long)this.data[i] & 0xffffffffL;
  1970. if ( i < m ){
  1971. c -= (long)other.data[i] & 0xffffffffL;
  1972. }
  1973. if ( ( r[i] = (int) c ) == 0 )
  1974. nzeros++;
  1975. else
  1976. nzeros = 0;
  1977. c >>= 32; // signed shift.
  1978. }
  1979. if ( c != 0L )
  1980. throw new RuntimeException("Assertion botch: borrow out of subtract");
  1981. while ( i < m )
  1982. if ( other.data[i++] != 0 )
  1983. throw new RuntimeException("Assertion botch: negative result of subtract");
  1984. return new FDBigInt( r, n-nzeros );
  1985. }
  1986. /*
  1987. * Compare FDBigInt with another FDBigInt. Return an integer
  1988. * >0: this > other
  1989. * 0: this == other
  1990. * <0: this < other
  1991. */
  1992. public int
  1993. cmp( FDBigInt other ){
  1994. int i;
  1995. if ( this.nWords > other.nWords ){
  1996. // if any of my high-order words is non-zero,
  1997. // then the answer is evident
  1998. int j = other.nWords-1;
  1999. for ( i = this.nWords-1; i > j ; i-- )
  2000. if ( this.data[i] != 0 ) return 1;
  2001. }else if ( this.nWords < other.nWords ){
  2002. // if any of other's high-order words is non-zero,
  2003. // then the answer is evident
  2004. int j = this.nWords-1;
  2005. for ( i = other.nWords-1; i > j ; i-- )
  2006. if ( other.data[i] != 0 ) return -1;
  2007. } else{
  2008. i = this.nWords-1;
  2009. }
  2010. for ( ; i > 0 ; i-- )
  2011. if ( this.data[i] != other.data[i] )
  2012. break;
  2013. // careful! want unsigned compare!
  2014. // use brute force here.
  2015. int a = this.data[i];
  2016. int b = other.data[i];
  2017. if ( a < 0 ){
  2018. // a is really big, unsigned
  2019. if ( b < 0 ){
  2020. return a-b; // both big, negative
  2021. } else {
  2022. return 1; // b not big, answer is obvious;
  2023. }
  2024. } else {
  2025. // a is not really big
  2026. if ( b < 0 ) {
  2027. // but b is really big
  2028. return -1;
  2029. } else {
  2030. return a - b;
  2031. }
  2032. }
  2033. }
  2034. /*
  2035. * Compute
  2036. * q = (int)( this / S )
  2037. * this = 10 * ( this mod S )
  2038. * Return q.
  2039. * This is the iteration step of digit development for output.
  2040. * We assume that S has been normalized, as above, and that
  2041. * "this" has been lshift'ed accordingly.
  2042. * Also assume, of course, that the result, q, can be expressed
  2043. * as an integer, 0 <= q < 10.
  2044. */
  2045. public int
  2046. quoRemIteration( FDBigInt S )throws IllegalArgumentException {
  2047. // ensure that this and S have the same number of
  2048. // digits. If S is properly normalized and q < 10 then
  2049. // this must be so.
  2050. if ( nWords != S.nWords ){
  2051. throw new IllegalArgumentException("disparate values");
  2052. }
  2053. // estimate q the obvious way. We will usually be
  2054. // right. If not, then we're only off by a little and
  2055. // will re-add.
  2056. int n = nWords-1;
  2057. long q = ((long)data[n]&0xffffffffL) / (long)S.data[n];
  2058. long diff = 0L;
  2059. for ( int i = 0; i <= n ; i++ ){
  2060. diff += ((long)data[i]&0xffffffffL) - q*((long)S.data[i]&0xffffffffL);
  2061. data[i] = (int)diff;
  2062. diff >>= 32; // N.B. SIGNED shift.
  2063. }
  2064. if ( diff != 0L ) {
  2065. // damn, damn, damn. q is too big.
  2066. // add S back in until this turns +. This should
  2067. // not be very many times!
  2068. long sum = 0L;
  2069. while ( sum == 0L ){
  2070. sum = 0L;
  2071. for ( int i = 0; i <= n; i++ ){
  2072. sum += ((long)data[i]&0xffffffffL) + ((long)S.data[i]&0xffffffffL);
  2073. data[i] = (int) sum;
  2074. sum >>= 32; // Signed or unsigned, answer is 0 or 1
  2075. }
  2076. /*
  2077. * Originally the following line read
  2078. * "if ( sum !=0 && sum != -1 )"
  2079. * but that would be wrong, because of the
  2080. * treatment of the two values as entirely unsigned,
  2081. * it would be impossible for a carry-out to be interpreted
  2082. * as -1 -- it would have to be a single-bit carry-out, or
  2083. * +1.
  2084. */
  2085. if ( sum !=0 && sum != 1 )
  2086. throw new RuntimeException("Assertion botch: "+sum+" carry out of division correction");
  2087. q -= 1;
  2088. }
  2089. }
  2090. // finally, we can multiply this by 10.
  2091. // it cannot overflow, right, as the high-order word has
  2092. // at least 4 high-order zeros!
  2093. long p = 0L;
  2094. for ( int i = 0; i <= n; i++ ){
  2095. p += 10*((long)data[i]&0xffffffffL);
  2096. data[i] = (int)p;
  2097. p >>= 32; // SIGNED shift.
  2098. }
  2099. if ( p != 0L )
  2100. throw new RuntimeException("Assertion botch: carry out of *10");
  2101. return (int)q;
  2102. }
  2103. public long
  2104. longValue(){
  2105. // if this can be represented as a long,
  2106. // return the value
  2107. int i;
  2108. for ( i = this.nWords-1; i > 1 ; i-- ){
  2109. if ( data[i] != 0 ){
  2110. throw new RuntimeException("Assertion botch: value too big");
  2111. }
  2112. }
  2113. switch(i){
  2114. case 1:
  2115. if ( data[1] < 0 )
  2116. throw new RuntimeException("Assertion botch: value too big");
  2117. return ((long)(data[1]) << 32) | ((long)data[0]&0xffffffffL);
  2118. case 0:
  2119. return ((long)data[0]&0xffffffffL);
  2120. default:
  2121. throw new RuntimeException("Assertion botch: longValue confused");
  2122. }
  2123. }
  2124. public String
  2125. toString() {
  2126. StringBuffer r = new StringBuffer(30);
  2127. r.append('[');
  2128. int i = Math.min( nWords-1, data.length-1) ;
  2129. if ( nWords > data.length ){
  2130. r.append( "("+data.length+"<"+nWords+"!)" );
  2131. }
  2132. for( ; i> 0 ; i-- ){
  2133. r.append( Integer.toHexString( data[i] ) );
  2134. r.append( (char) ' ' );
  2135. }
  2136. r.append( Integer.toHexString( data[0] ) );
  2137. r.append( (char) ']' );
  2138. return new String( r );
  2139. }
  2140. }