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