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