PageRenderTime 59ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/java-1.7.0-openjdk/openjdk/jdk/src/share/classes/sun/misc/FloatingDecimal.java

#
Java | 2878 lines | 1684 code | 168 blank | 1026 comment | 501 complexity | 40a3ec6f37808c8096fcc501c80ec229 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.0, LGPL-2.0
  1. /*
  2. * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation. Oracle designates this
  8. * particular file as subject to the "Classpath" exception as provided
  9. * by Oracle in the LICENSE file that accompanied this code.
  10. *
  11. * This code is distributed in the hope that it will be useful, but WITHOUT
  12. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  14. * version 2 for more details (a copy is included in the LICENSE file that
  15. * accompanied this code).
  16. *
  17. * You should have received a copy of the GNU General Public License version
  18. * 2 along with this work; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20. *
  21. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22. * or visit www.oracle.com if you need additional information or have any
  23. * questions.
  24. */
  25. package sun.misc;
  26. import sun.misc.FpUtils;
  27. import sun.misc.DoubleConsts;
  28. import sun.misc.FloatConsts;
  29. import java.util.regex.*;
  30. public class FloatingDecimal{
  31. boolean isExceptional;
  32. boolean isNegative;
  33. int decExponent;
  34. char digits[];
  35. int nDigits;
  36. int bigIntExp;
  37. int bigIntNBits;
  38. boolean mustSetRoundDir = false;
  39. boolean fromHex = false;
  40. int roundDir = 0; // set by doubleValue
  41. private FloatingDecimal( boolean negSign, int decExponent, char []digits, int n, boolean e )
  42. {
  43. isNegative = negSign;
  44. isExceptional = e;
  45. this.decExponent = decExponent;
  46. this.digits = digits;
  47. this.nDigits = n;
  48. }
  49. /*
  50. * Constants of the implementation
  51. * Most are IEEE-754 related.
  52. * (There are more really boring constants at the end.)
  53. */
  54. static final long signMask = 0x8000000000000000L;
  55. static final long expMask = 0x7ff0000000000000L;
  56. static final long fractMask= ~(signMask|expMask);
  57. static final int expShift = 52;
  58. static final int expBias = 1023;
  59. static final long fractHOB = ( 1L<<expShift ); // assumed High-Order bit
  60. static final long expOne = ((long)expBias)<<expShift; // exponent of 1.0
  61. static final int maxSmallBinExp = 62;
  62. static final int minSmallBinExp = -( 63 / 3 );
  63. static final int maxDecimalDigits = 15;
  64. static final int maxDecimalExponent = 308;
  65. static final int minDecimalExponent = -324;
  66. static final int bigDecimalExponent = 324; // i.e. abs(minDecimalExponent)
  67. static final long highbyte = 0xff00000000000000L;
  68. static final long highbit = 0x8000000000000000L;
  69. static final long lowbytes = ~highbyte;
  70. static final int singleSignMask = 0x80000000;
  71. static final int singleExpMask = 0x7f800000;
  72. static final int singleFractMask = ~(singleSignMask|singleExpMask);
  73. static final int singleExpShift = 23;
  74. static final int singleFractHOB = 1<<singleExpShift;
  75. static final int singleExpBias = 127;
  76. static final int singleMaxDecimalDigits = 7;
  77. static final int singleMaxDecimalExponent = 38;
  78. static final int singleMinDecimalExponent = -45;
  79. static final int intDecimalDigits = 9;
  80. /*
  81. * count number of bits from high-order 1 bit to low-order 1 bit,
  82. * inclusive.
  83. */
  84. private static int
  85. countBits( long v ){
  86. //
  87. // the strategy is to shift until we get a non-zero sign bit
  88. // then shift until we have no bits left, counting the difference.
  89. // we do byte shifting as a hack. Hope it helps.
  90. //
  91. if ( v == 0L ) return 0;
  92. while ( ( v & highbyte ) == 0L ){
  93. v <<= 8;
  94. }
  95. while ( v > 0L ) { // i.e. while ((v&highbit) == 0L )
  96. v <<= 1;
  97. }
  98. int n = 0;
  99. while (( v & lowbytes ) != 0L ){
  100. v <<= 8;
  101. n += 8;
  102. }
  103. while ( v != 0L ){
  104. v <<= 1;
  105. n += 1;
  106. }
  107. return n;
  108. }
  109. /*
  110. * Keep big powers of 5 handy for future reference.
  111. */
  112. private static FDBigInt b5p[];
  113. private static synchronized FDBigInt
  114. big5pow( int p ){
  115. assert p >= 0 : p; // negative power of 5
  116. if ( b5p == null ){
  117. b5p = new FDBigInt[ p+1 ];
  118. }else if (b5p.length <= p ){
  119. FDBigInt t[] = new FDBigInt[ p+1 ];
  120. System.arraycopy( b5p, 0, t, 0, b5p.length );
  121. b5p = t;
  122. }
  123. if ( b5p[p] != null )
  124. return b5p[p];
  125. else if ( p < small5pow.length )
  126. return b5p[p] = new FDBigInt( small5pow[p] );
  127. else if ( p < long5pow.length )
  128. return b5p[p] = new FDBigInt( long5pow[p] );
  129. else {
  130. // construct the value.
  131. // recursively.
  132. int q, r;
  133. // in order to compute 5^p,
  134. // compute its square root, 5^(p/2) and square.
  135. // or, let q = p / 2, r = p -q, then
  136. // 5^p = 5^(q+r) = 5^q * 5^r
  137. q = p >> 1;
  138. r = p - q;
  139. FDBigInt bigq = b5p[q];
  140. if ( bigq == null )
  141. bigq = big5pow ( q );
  142. if ( r < small5pow.length ){
  143. return (b5p[p] = bigq.mult( small5pow[r] ) );
  144. }else{
  145. FDBigInt bigr = b5p[ r ];
  146. if ( bigr == null )
  147. bigr = big5pow( r );
  148. return (b5p[p] = bigq.mult( bigr ) );
  149. }
  150. }
  151. }
  152. //
  153. // a common operation
  154. //
  155. private static FDBigInt
  156. multPow52( FDBigInt v, int p5, int p2 ){
  157. if ( p5 != 0 ){
  158. if ( p5 < small5pow.length ){
  159. v = v.mult( small5pow[p5] );
  160. } else {
  161. v = v.mult( big5pow( p5 ) );
  162. }
  163. }
  164. if ( p2 != 0 ){
  165. v.lshiftMe( p2 );
  166. }
  167. return v;
  168. }
  169. //
  170. // another common operation
  171. //
  172. private static FDBigInt
  173. constructPow52( int p5, int p2 ){
  174. FDBigInt v = new FDBigInt( big5pow( p5 ) );
  175. if ( p2 != 0 ){
  176. v.lshiftMe( p2 );
  177. }
  178. return v;
  179. }
  180. /*
  181. * Make a floating double into a FDBigInt.
  182. * This could also be structured as a FDBigInt
  183. * constructor, but we'd have to build a lot of knowledge
  184. * about floating-point representation into it, and we don't want to.
  185. *
  186. * AS A SIDE EFFECT, THIS METHOD WILL SET THE INSTANCE VARIABLES
  187. * bigIntExp and bigIntNBits
  188. *
  189. */
  190. private FDBigInt
  191. doubleToBigInt( double dval ){
  192. long lbits = Double.doubleToLongBits( dval ) & ~signMask;
  193. int binexp = (int)(lbits >>> expShift);
  194. lbits &= fractMask;
  195. if ( binexp > 0 ){
  196. lbits |= fractHOB;
  197. } else {
  198. assert lbits != 0L : lbits; // doubleToBigInt(0.0)
  199. binexp +=1;
  200. while ( (lbits & fractHOB ) == 0L){
  201. lbits <<= 1;
  202. binexp -= 1;
  203. }
  204. }
  205. binexp -= expBias;
  206. int nbits = countBits( lbits );
  207. /*
  208. * We now know where the high-order 1 bit is,
  209. * and we know how many there are.
  210. */
  211. int lowOrderZeros = expShift+1-nbits;
  212. lbits >>>= lowOrderZeros;
  213. bigIntExp = binexp+1-nbits;
  214. bigIntNBits = nbits;
  215. return new FDBigInt( lbits );
  216. }
  217. /*
  218. * Compute a number that is the ULP of the given value,
  219. * for purposes of addition/subtraction. Generally easy.
  220. * More difficult if subtracting and the argument
  221. * is a normalized a power of 2, as the ULP changes at these points.
  222. */
  223. private static double ulp( double dval, boolean subtracting ){
  224. long lbits = Double.doubleToLongBits( dval ) & ~signMask;
  225. int binexp = (int)(lbits >>> expShift);
  226. double ulpval;
  227. if ( subtracting && ( binexp >= expShift ) && ((lbits&fractMask) == 0L) ){
  228. // for subtraction from normalized, powers of 2,
  229. // use next-smaller exponent
  230. binexp -= 1;
  231. }
  232. if ( binexp > expShift ){
  233. ulpval = Double.longBitsToDouble( ((long)(binexp-expShift))<<expShift );
  234. } else if ( binexp == 0 ){
  235. ulpval = Double.MIN_VALUE;
  236. } else {
  237. ulpval = Double.longBitsToDouble( 1L<<(binexp-1) );
  238. }
  239. if ( subtracting ) ulpval = - ulpval;
  240. return ulpval;
  241. }
  242. /*
  243. * Round a double to a float.
  244. * In addition to the fraction bits of the double,
  245. * look at the class instance variable roundDir,
  246. * which should help us avoid double-rounding error.
  247. * roundDir was set in hardValueOf if the estimate was
  248. * close enough, but not exact. It tells us which direction
  249. * of rounding is preferred.
  250. */
  251. float
  252. stickyRound( double dval ){
  253. long lbits = Double.doubleToLongBits( dval );
  254. long binexp = lbits & expMask;
  255. if ( binexp == 0L || binexp == expMask ){
  256. // what we have here is special.
  257. // don't worry, the right thing will happen.
  258. return (float) dval;
  259. }
  260. lbits += (long)roundDir; // hack-o-matic.
  261. return (float)Double.longBitsToDouble( lbits );
  262. }
  263. /*
  264. * This is the easy subcase --
  265. * all the significant bits, after scaling, are held in lvalue.
  266. * negSign and decExponent tell us what processing and scaling
  267. * has already been done. Exceptional cases have already been
  268. * stripped out.
  269. * In particular:
  270. * lvalue is a finite number (not Inf, nor NaN)
  271. * lvalue > 0L (not zero, nor negative).
  272. *
  273. * The only reason that we develop the digits here, rather than
  274. * calling on Long.toString() is that we can do it a little faster,
  275. * and besides want to treat trailing 0s specially. If Long.toString
  276. * changes, we should re-evaluate this strategy!
  277. */
  278. private void
  279. developLongDigits( int decExponent, long lvalue, long insignificant ){
  280. char digits[];
  281. int ndigits;
  282. int digitno;
  283. int c;
  284. //
  285. // Discard non-significant low-order bits, while rounding,
  286. // up to insignificant value.
  287. int i;
  288. for ( i = 0; insignificant >= 10L; i++ )
  289. insignificant /= 10L;
  290. if ( i != 0 ){
  291. long pow10 = long5pow[i] << i; // 10^i == 5^i * 2^i;
  292. long residue = lvalue % pow10;
  293. lvalue /= pow10;
  294. decExponent += i;
  295. if ( residue >= (pow10>>1) ){
  296. // round up based on the low-order bits we're discarding
  297. lvalue++;
  298. }
  299. }
  300. if ( lvalue <= Integer.MAX_VALUE ){
  301. assert lvalue > 0L : lvalue; // lvalue <= 0
  302. // even easier subcase!
  303. // can do int arithmetic rather than long!
  304. int ivalue = (int)lvalue;
  305. ndigits = 10;
  306. digits = (char[])(perThreadBuffer.get());
  307. digitno = ndigits-1;
  308. c = ivalue%10;
  309. ivalue /= 10;
  310. while ( c == 0 ){
  311. decExponent++;
  312. c = ivalue%10;
  313. ivalue /= 10;
  314. }
  315. while ( ivalue != 0){
  316. digits[digitno--] = (char)(c+'0');
  317. decExponent++;
  318. c = ivalue%10;
  319. ivalue /= 10;
  320. }
  321. digits[digitno] = (char)(c+'0');
  322. } else {
  323. // same algorithm as above (same bugs, too )
  324. // but using long arithmetic.
  325. ndigits = 20;
  326. digits = (char[])(perThreadBuffer.get());
  327. digitno = ndigits-1;
  328. c = (int)(lvalue%10L);
  329. lvalue /= 10L;
  330. while ( c == 0 ){
  331. decExponent++;
  332. c = (int)(lvalue%10L);
  333. lvalue /= 10L;
  334. }
  335. while ( lvalue != 0L ){
  336. digits[digitno--] = (char)(c+'0');
  337. decExponent++;
  338. c = (int)(lvalue%10L);
  339. lvalue /= 10;
  340. }
  341. digits[digitno] = (char)(c+'0');
  342. }
  343. char result [];
  344. ndigits -= digitno;
  345. result = new char[ ndigits ];
  346. System.arraycopy( digits, digitno, result, 0, ndigits );
  347. this.digits = result;
  348. this.decExponent = decExponent+1;
  349. this.nDigits = ndigits;
  350. }
  351. //
  352. // add one to the least significant digit.
  353. // in the unlikely event there is a carry out,
  354. // deal with it.
  355. // assert that this will only happen where there
  356. // is only one digit, e.g. (float)1e-44 seems to do it.
  357. //
  358. private void
  359. roundup(){
  360. int i;
  361. int q = digits[ i = (nDigits-1)];
  362. if ( q == '9' ){
  363. while ( q == '9' && i > 0 ){
  364. digits[i] = '0';
  365. q = digits[--i];
  366. }
  367. if ( q == '9' ){
  368. // carryout! High-order 1, rest 0s, larger exp.
  369. decExponent += 1;
  370. digits[0] = '1';
  371. return;
  372. }
  373. // else fall through.
  374. }
  375. digits[i] = (char)(q+1);
  376. }
  377. /*
  378. * FIRST IMPORTANT CONSTRUCTOR: DOUBLE
  379. */
  380. public FloatingDecimal( double d )
  381. {
  382. long dBits = Double.doubleToLongBits( d );
  383. long fractBits;
  384. int binExp;
  385. int nSignificantBits;
  386. // discover and delete sign
  387. if ( (dBits&signMask) != 0 ){
  388. isNegative = true;
  389. dBits ^= signMask;
  390. } else {
  391. isNegative = false;
  392. }
  393. // Begin to unpack
  394. // Discover obvious special cases of NaN and Infinity.
  395. binExp = (int)( (dBits&expMask) >> expShift );
  396. fractBits = dBits&fractMask;
  397. if ( binExp == (int)(expMask>>expShift) ) {
  398. isExceptional = true;
  399. if ( fractBits == 0L ){
  400. digits = infinity;
  401. } else {
  402. digits = notANumber;
  403. isNegative = false; // NaN has no sign!
  404. }
  405. nDigits = digits.length;
  406. return;
  407. }
  408. isExceptional = false;
  409. // Finish unpacking
  410. // Normalize denormalized numbers.
  411. // Insert assumed high-order bit for normalized numbers.
  412. // Subtract exponent bias.
  413. if ( binExp == 0 ){
  414. if ( fractBits == 0L ){
  415. // not a denorm, just a 0!
  416. decExponent = 0;
  417. digits = zero;
  418. nDigits = 1;
  419. return;
  420. }
  421. while ( (fractBits&fractHOB) == 0L ){
  422. fractBits <<= 1;
  423. binExp -= 1;
  424. }
  425. nSignificantBits = expShift + binExp +1; // recall binExp is - shift count.
  426. binExp += 1;
  427. } else {
  428. fractBits |= fractHOB;
  429. nSignificantBits = expShift+1;
  430. }
  431. binExp -= expBias;
  432. // call the routine that actually does all the hard work.
  433. dtoa( binExp, fractBits, nSignificantBits );
  434. }
  435. /*
  436. * SECOND IMPORTANT CONSTRUCTOR: SINGLE
  437. */
  438. public FloatingDecimal( float f )
  439. {
  440. int fBits = Float.floatToIntBits( f );
  441. int fractBits;
  442. int binExp;
  443. int nSignificantBits;
  444. // discover and delete sign
  445. if ( (fBits&singleSignMask) != 0 ){
  446. isNegative = true;
  447. fBits ^= singleSignMask;
  448. } else {
  449. isNegative = false;
  450. }
  451. // Begin to unpack
  452. // Discover obvious special cases of NaN and Infinity.
  453. binExp = (int)( (fBits&singleExpMask) >> singleExpShift );
  454. fractBits = fBits&singleFractMask;
  455. if ( binExp == (int)(singleExpMask>>singleExpShift) ) {
  456. isExceptional = true;
  457. if ( fractBits == 0L ){
  458. digits = infinity;
  459. } else {
  460. digits = notANumber;
  461. isNegative = false; // NaN has no sign!
  462. }
  463. nDigits = digits.length;
  464. return;
  465. }
  466. isExceptional = false;
  467. // Finish unpacking
  468. // Normalize denormalized numbers.
  469. // Insert assumed high-order bit for normalized numbers.
  470. // Subtract exponent bias.
  471. if ( binExp == 0 ){
  472. if ( fractBits == 0 ){
  473. // not a denorm, just a 0!
  474. decExponent = 0;
  475. digits = zero;
  476. nDigits = 1;
  477. return;
  478. }
  479. while ( (fractBits&singleFractHOB) == 0 ){
  480. fractBits <<= 1;
  481. binExp -= 1;
  482. }
  483. nSignificantBits = singleExpShift + binExp +1; // recall binExp is - shift count.
  484. binExp += 1;
  485. } else {
  486. fractBits |= singleFractHOB;
  487. nSignificantBits = singleExpShift+1;
  488. }
  489. binExp -= singleExpBias;
  490. // call the routine that actually does all the hard work.
  491. dtoa( binExp, ((long)fractBits)<<(expShift-singleExpShift), nSignificantBits );
  492. }
  493. private void
  494. dtoa( int binExp, long fractBits, int nSignificantBits )
  495. {
  496. int nFractBits; // number of significant bits of fractBits;
  497. int nTinyBits; // number of these to the right of the point.
  498. int decExp;
  499. // Examine number. Determine if it is an easy case,
  500. // which we can do pretty trivially using float/long conversion,
  501. // or whether we must do real work.
  502. nFractBits = countBits( fractBits );
  503. nTinyBits = Math.max( 0, nFractBits - binExp - 1 );
  504. if ( binExp <= maxSmallBinExp && binExp >= minSmallBinExp ){
  505. // Look more closely at the number to decide if,
  506. // with scaling by 10^nTinyBits, the result will fit in
  507. // a long.
  508. if ( (nTinyBits < long5pow.length) && ((nFractBits + n5bits[nTinyBits]) < 64 ) ){
  509. /*
  510. * We can do this:
  511. * take the fraction bits, which are normalized.
  512. * (a) nTinyBits == 0: Shift left or right appropriately
  513. * to align the binary point at the extreme right, i.e.
  514. * where a long int point is expected to be. The integer
  515. * result is easily converted to a string.
  516. * (b) nTinyBits > 0: Shift right by expShift-nFractBits,
  517. * which effectively converts to long and scales by
  518. * 2^nTinyBits. Then multiply by 5^nTinyBits to
  519. * complete the scaling. We know this won't overflow
  520. * because we just counted the number of bits necessary
  521. * in the result. The integer you get from this can
  522. * then be converted to a string pretty easily.
  523. */
  524. long halfULP;
  525. if ( nTinyBits == 0 ) {
  526. if ( binExp > nSignificantBits ){
  527. halfULP = 1L << ( binExp-nSignificantBits-1);
  528. } else {
  529. halfULP = 0L;
  530. }
  531. if ( binExp >= expShift ){
  532. fractBits <<= (binExp-expShift);
  533. } else {
  534. fractBits >>>= (expShift-binExp) ;
  535. }
  536. developLongDigits( 0, fractBits, halfULP );
  537. return;
  538. }
  539. /*
  540. * The following causes excess digits to be printed
  541. * out in the single-float case. Our manipulation of
  542. * halfULP here is apparently not correct. If we
  543. * better understand how this works, perhaps we can
  544. * use this special case again. But for the time being,
  545. * we do not.
  546. * else {
  547. * fractBits >>>= expShift+1-nFractBits;
  548. * fractBits *= long5pow[ nTinyBits ];
  549. * halfULP = long5pow[ nTinyBits ] >> (1+nSignificantBits-nFractBits);
  550. * developLongDigits( -nTinyBits, fractBits, halfULP );
  551. * return;
  552. * }
  553. */
  554. }
  555. }
  556. /*
  557. * This is the hard case. We are going to compute large positive
  558. * integers B and S and integer decExp, s.t.
  559. * d = ( B / S ) * 10^decExp
  560. * 1 <= B / S < 10
  561. * Obvious choices are:
  562. * decExp = floor( log10(d) )
  563. * B = d * 2^nTinyBits * 10^max( 0, -decExp )
  564. * S = 10^max( 0, decExp) * 2^nTinyBits
  565. * (noting that nTinyBits has already been forced to non-negative)
  566. * I am also going to compute a large positive integer
  567. * M = (1/2^nSignificantBits) * 2^nTinyBits * 10^max( 0, -decExp )
  568. * i.e. M is (1/2) of the ULP of d, scaled like B.
  569. * When we iterate through dividing B/S and picking off the
  570. * quotient bits, we will know when to stop when the remainder
  571. * is <= M.
  572. *
  573. * We keep track of powers of 2 and powers of 5.
  574. */
  575. /*
  576. * Estimate decimal exponent. (If it is small-ish,
  577. * we could double-check.)
  578. *
  579. * First, scale the mantissa bits such that 1 <= d2 < 2.
  580. * We are then going to estimate
  581. * log10(d2) ~=~ (d2-1.5)/1.5 + log(1.5)
  582. * and so we can estimate
  583. * log10(d) ~=~ log10(d2) + binExp * log10(2)
  584. * take the floor and call it decExp.
  585. * FIXME -- use more precise constants here. It costs no more.
  586. */
  587. double d2 = Double.longBitsToDouble(
  588. expOne | ( fractBits &~ fractHOB ) );
  589. decExp = (int)Math.floor(
  590. (d2-1.5D)*0.289529654D + 0.176091259 + (double)binExp * 0.301029995663981 );
  591. int B2, B5; // powers of 2 and powers of 5, respectively, in B
  592. int S2, S5; // powers of 2 and powers of 5, respectively, in S
  593. int M2, M5; // powers of 2 and powers of 5, respectively, in M
  594. int Bbits; // binary digits needed to represent B, approx.
  595. int tenSbits; // binary digits needed to represent 10*S, approx.
  596. FDBigInt Sval, Bval, Mval;
  597. B5 = Math.max( 0, -decExp );
  598. B2 = B5 + nTinyBits + binExp;
  599. S5 = Math.max( 0, decExp );
  600. S2 = S5 + nTinyBits;
  601. M5 = B5;
  602. M2 = B2 - nSignificantBits;
  603. /*
  604. * the long integer fractBits contains the (nFractBits) interesting
  605. * bits from the mantissa of d ( hidden 1 added if necessary) followed
  606. * by (expShift+1-nFractBits) zeros. In the interest of compactness,
  607. * I will shift out those zeros before turning fractBits into a
  608. * FDBigInt. The resulting whole number will be
  609. * d * 2^(nFractBits-1-binExp).
  610. */
  611. fractBits >>>= (expShift+1-nFractBits);
  612. B2 -= nFractBits-1;
  613. int common2factor = Math.min( B2, S2 );
  614. B2 -= common2factor;
  615. S2 -= common2factor;
  616. M2 -= common2factor;
  617. /*
  618. * HACK!! For exact powers of two, the next smallest number
  619. * is only half as far away as we think (because the meaning of
  620. * ULP changes at power-of-two bounds) for this reason, we
  621. * hack M2. Hope this works.
  622. */
  623. if ( nFractBits == 1 )
  624. M2 -= 1;
  625. if ( M2 < 0 ){
  626. // oops.
  627. // since we cannot scale M down far enough,
  628. // we must scale the other values up.
  629. B2 -= M2;
  630. S2 -= M2;
  631. M2 = 0;
  632. }
  633. /*
  634. * Construct, Scale, iterate.
  635. * Some day, we'll write a stopping test that takes
  636. * account of the asymmetry of the spacing of floating-point
  637. * numbers below perfect powers of 2
  638. * 26 Sept 96 is not that day.
  639. * So we use a symmetric test.
  640. */
  641. char digits[] = this.digits = new char[18];
  642. int ndigit = 0;
  643. boolean low, high;
  644. long lowDigitDifference;
  645. int q;
  646. /*
  647. * Detect the special cases where all the numbers we are about
  648. * to compute will fit in int or long integers.
  649. * In these cases, we will avoid doing FDBigInt arithmetic.
  650. * We use the same algorithms, except that we "normalize"
  651. * our FDBigInts before iterating. This is to make division easier,
  652. * as it makes our fist guess (quotient of high-order words)
  653. * more accurate!
  654. *
  655. * Some day, we'll write a stopping test that takes
  656. * account of the asymmetry of the spacing of floating-point
  657. * numbers below perfect powers of 2
  658. * 26 Sept 96 is not that day.
  659. * So we use a symmetric test.
  660. */
  661. Bbits = nFractBits + B2 + (( B5 < n5bits.length )? n5bits[B5] : ( B5*3 ));
  662. tenSbits = S2+1 + (( (S5+1) < n5bits.length )? n5bits[(S5+1)] : ( (S5+1)*3 ));
  663. if ( Bbits < 64 && tenSbits < 64){
  664. if ( Bbits < 32 && tenSbits < 32){
  665. // wa-hoo! They're all ints!
  666. int b = ((int)fractBits * small5pow[B5] ) << B2;
  667. int s = small5pow[S5] << S2;
  668. int m = small5pow[M5] << M2;
  669. int tens = s * 10;
  670. /*
  671. * Unroll the first iteration. If our decExp estimate
  672. * was too high, our first quotient will be zero. In this
  673. * case, we discard it and decrement decExp.
  674. */
  675. ndigit = 0;
  676. q = b / s;
  677. b = 10 * ( b % s );
  678. m *= 10;
  679. low = (b < m );
  680. high = (b+m > tens );
  681. assert q < 10 : q; // excessively large digit
  682. if ( (q == 0) && ! high ){
  683. // oops. Usually ignore leading zero.
  684. decExp--;
  685. } else {
  686. digits[ndigit++] = (char)('0' + q);
  687. }
  688. /*
  689. * HACK! Java spec sez that we always have at least
  690. * one digit after the . in either F- or E-form output.
  691. * Thus we will need more than one digit if we're using
  692. * E-form
  693. */
  694. if ( decExp < -3 || decExp >= 8 ){
  695. high = low = false;
  696. }
  697. while( ! low && ! high ){
  698. q = b / s;
  699. b = 10 * ( b % s );
  700. m *= 10;
  701. assert q < 10 : q; // excessively large digit
  702. if ( m > 0L ){
  703. low = (b < m );
  704. high = (b+m > tens );
  705. } else {
  706. // hack -- m might overflow!
  707. // in this case, it is certainly > b,
  708. // which won't
  709. // and b+m > tens, too, since that has overflowed
  710. // either!
  711. low = true;
  712. high = true;
  713. }
  714. digits[ndigit++] = (char)('0' + q);
  715. }
  716. lowDigitDifference = (b<<1) - tens;
  717. } else {
  718. // still good! they're all longs!
  719. long b = (fractBits * long5pow[B5] ) << B2;
  720. long s = long5pow[S5] << S2;
  721. long m = long5pow[M5] << M2;
  722. long tens = s * 10L;
  723. /*
  724. * Unroll the first iteration. If our decExp estimate
  725. * was too high, our first quotient will be zero. In this
  726. * case, we discard it and decrement decExp.
  727. */
  728. ndigit = 0;
  729. q = (int) ( b / s );
  730. b = 10L * ( b % s );
  731. m *= 10L;
  732. low = (b < m );
  733. high = (b+m > tens );
  734. assert q < 10 : q; // excessively large digit
  735. if ( (q == 0) && ! high ){
  736. // oops. Usually ignore leading zero.
  737. decExp--;
  738. } else {
  739. digits[ndigit++] = (char)('0' + q);
  740. }
  741. /*
  742. * HACK! Java spec sez that we always have at least
  743. * one digit after the . in either F- or E-form output.
  744. * Thus we will need more than one digit if we're using
  745. * E-form
  746. */
  747. if ( decExp < -3 || decExp >= 8 ){
  748. high = low = false;
  749. }
  750. while( ! low && ! high ){
  751. q = (int) ( b / s );
  752. b = 10 * ( b % s );
  753. m *= 10;
  754. assert q < 10 : q; // excessively large digit
  755. if ( m > 0L ){
  756. low = (b < m );
  757. high = (b+m > tens );
  758. } else {
  759. // hack -- m might overflow!
  760. // in this case, it is certainly > b,
  761. // which won't
  762. // and b+m > tens, too, since that has overflowed
  763. // either!
  764. low = true;
  765. high = true;
  766. }
  767. digits[ndigit++] = (char)('0' + q);
  768. }
  769. lowDigitDifference = (b<<1) - tens;
  770. }
  771. } else {
  772. FDBigInt tenSval;
  773. int shiftBias;
  774. /*
  775. * We really must do FDBigInt arithmetic.
  776. * Fist, construct our FDBigInt initial values.
  777. */
  778. Bval = multPow52( new FDBigInt( fractBits ), B5, B2 );
  779. Sval = constructPow52( S5, S2 );
  780. Mval = constructPow52( M5, M2 );
  781. // normalize so that division works better
  782. Bval.lshiftMe( shiftBias = Sval.normalizeMe() );
  783. Mval.lshiftMe( shiftBias );
  784. tenSval = Sval.mult( 10 );
  785. /*
  786. * Unroll the first iteration. If our decExp estimate
  787. * was too high, our first quotient will be zero. In this
  788. * case, we discard it and decrement decExp.
  789. */
  790. ndigit = 0;
  791. q = Bval.quoRemIteration( Sval );
  792. Mval = Mval.mult( 10 );
  793. low = (Bval.cmp( Mval ) < 0);
  794. high = (Bval.add( Mval ).cmp( tenSval ) > 0 );
  795. assert q < 10 : q; // excessively large digit
  796. if ( (q == 0) && ! high ){
  797. // oops. Usually ignore leading zero.
  798. decExp--;
  799. } else {
  800. digits[ndigit++] = (char)('0' + q);
  801. }
  802. /*
  803. * HACK! Java spec sez that we always have at least
  804. * one digit after the . in either F- or E-form output.
  805. * Thus we will need more than one digit if we're using
  806. * E-form
  807. */
  808. if ( decExp < -3 || decExp >= 8 ){
  809. high = low = false;
  810. }
  811. while( ! low && ! high ){
  812. q = Bval.quoRemIteration( Sval );
  813. Mval = Mval.mult( 10 );
  814. assert q < 10 : q; // excessively large digit
  815. low = (Bval.cmp( Mval ) < 0);
  816. high = (Bval.add( Mval ).cmp( tenSval ) > 0 );
  817. digits[ndigit++] = (char)('0' + q);
  818. }
  819. if ( high && low ){
  820. Bval.lshiftMe(1);
  821. lowDigitDifference = Bval.cmp(tenSval);
  822. } else
  823. lowDigitDifference = 0L; // this here only for flow analysis!
  824. }
  825. this.decExponent = decExp+1;
  826. this.digits = digits;
  827. this.nDigits = ndigit;
  828. /*
  829. * Last digit gets rounded based on stopping condition.
  830. */
  831. if ( high ){
  832. if ( low ){
  833. if ( lowDigitDifference == 0L ){
  834. // it's a tie!
  835. // choose based on which digits we like.
  836. if ( (digits[nDigits-1]&1) != 0 ) roundup();
  837. } else if ( lowDigitDifference > 0 ){
  838. roundup();
  839. }
  840. } else {
  841. roundup();
  842. }
  843. }
  844. }
  845. public String
  846. toString(){
  847. // most brain-dead version
  848. StringBuffer result = new StringBuffer( nDigits+8 );
  849. if ( isNegative ){ result.append( '-' ); }
  850. if ( isExceptional ){
  851. result.append( digits, 0, nDigits );
  852. } else {
  853. result.append( "0.");
  854. result.append( digits, 0, nDigits );
  855. result.append('e');
  856. result.append( decExponent );
  857. }
  858. return new String(result);
  859. }
  860. public String toJavaFormatString() {
  861. char result[] = (char[])(perThreadBuffer.get());
  862. int i = getChars(result);
  863. return new String(result, 0, i);
  864. }
  865. private int getChars(char[] result) {
  866. assert nDigits <= 19 : nDigits; // generous bound on size of nDigits
  867. int i = 0;
  868. if (isNegative) { result[0] = '-'; i = 1; }
  869. if (isExceptional) {
  870. System.arraycopy(digits, 0, result, i, nDigits);
  871. i += nDigits;
  872. } else {
  873. if (decExponent > 0 && decExponent < 8) {
  874. // print digits.digits.
  875. int charLength = Math.min(nDigits, decExponent);
  876. System.arraycopy(digits, 0, result, i, charLength);
  877. i += charLength;
  878. if (charLength < decExponent) {
  879. charLength = decExponent-charLength;
  880. System.arraycopy(zero, 0, result, i, charLength);
  881. i += charLength;
  882. result[i++] = '.';
  883. result[i++] = '0';
  884. } else {
  885. result[i++] = '.';
  886. if (charLength < nDigits) {
  887. int t = nDigits - charLength;
  888. System.arraycopy(digits, charLength, result, i, t);
  889. i += t;
  890. } else {
  891. result[i++] = '0';
  892. }
  893. }
  894. } else if (decExponent <=0 && decExponent > -3) {
  895. result[i++] = '0';
  896. result[i++] = '.';
  897. if (decExponent != 0) {
  898. System.arraycopy(zero, 0, result, i, -decExponent);
  899. i -= decExponent;
  900. }
  901. System.arraycopy(digits, 0, result, i, nDigits);
  902. i += nDigits;
  903. } else {
  904. result[i++] = digits[0];
  905. result[i++] = '.';
  906. if (nDigits > 1) {
  907. System.arraycopy(digits, 1, result, i, nDigits-1);
  908. i += nDigits-1;
  909. } else {
  910. result[i++] = '0';
  911. }
  912. result[i++] = 'E';
  913. int e;
  914. if (decExponent <= 0) {
  915. result[i++] = '-';
  916. e = -decExponent+1;
  917. } else {
  918. e = decExponent-1;
  919. }
  920. // decExponent has 1, 2, or 3, digits
  921. if (e <= 9) {
  922. result[i++] = (char)(e+'0');
  923. } else if (e <= 99) {
  924. result[i++] = (char)(e/10 +'0');
  925. result[i++] = (char)(e%10 + '0');
  926. } else {
  927. result[i++] = (char)(e/100+'0');
  928. e %= 100;
  929. result[i++] = (char)(e/10+'0');
  930. result[i++] = (char)(e%10 + '0');
  931. }
  932. }
  933. }
  934. return i;
  935. }
  936. // Per-thread buffer for string/stringbuffer conversion
  937. private static ThreadLocal perThreadBuffer = new ThreadLocal() {
  938. protected synchronized Object initialValue() {
  939. return new char[26];
  940. }
  941. };
  942. public void appendTo(Appendable buf) {
  943. char result[] = (char[])(perThreadBuffer.get());
  944. int i = getChars(result);
  945. if (buf instanceof StringBuilder)
  946. ((StringBuilder) buf).append(result, 0, i);
  947. else if (buf instanceof StringBuffer)
  948. ((StringBuffer) buf).append(result, 0, i);
  949. else
  950. assert false;
  951. }
  952. public static FloatingDecimal
  953. readJavaFormatString( String in ) throws NumberFormatException {
  954. boolean isNegative = false;
  955. boolean signSeen = false;
  956. int decExp;
  957. char c;
  958. parseNumber:
  959. try{
  960. in = in.trim(); // don't fool around with white space.
  961. // throws NullPointerException if null
  962. int l = in.length();
  963. if ( l == 0 ) throw new NumberFormatException("empty String");
  964. int i = 0;
  965. switch ( c = in.charAt( i ) ){
  966. case '-':
  967. isNegative = true;
  968. //FALLTHROUGH
  969. case '+':
  970. i++;
  971. signSeen = true;
  972. }
  973. // Check for NaN and Infinity strings
  974. c = in.charAt(i);
  975. if(c == 'N' || c == 'I') { // possible NaN or infinity
  976. boolean potentialNaN = false;
  977. char targetChars[] = null; // char array of "NaN" or "Infinity"
  978. if(c == 'N') {
  979. targetChars = notANumber;
  980. potentialNaN = true;
  981. } else {
  982. targetChars = infinity;
  983. }
  984. // compare Input string to "NaN" or "Infinity"
  985. int j = 0;
  986. while(i < l && j < targetChars.length) {
  987. if(in.charAt(i) == targetChars[j]) {
  988. i++; j++;
  989. }
  990. else // something is amiss, throw exception
  991. break parseNumber;
  992. }
  993. // For the candidate string to be a NaN or infinity,
  994. // all characters in input string and target char[]
  995. // must be matched ==> j must equal targetChars.length
  996. // and i must equal l
  997. if( (j == targetChars.length) && (i == l) ) { // return NaN or infinity
  998. return (potentialNaN ? new FloatingDecimal(Double.NaN) // NaN has no sign
  999. : new FloatingDecimal(isNegative?
  1000. Double.NEGATIVE_INFINITY:
  1001. Double.POSITIVE_INFINITY)) ;
  1002. }
  1003. else { // something went wrong, throw exception
  1004. break parseNumber;
  1005. }
  1006. } else if (c == '0') { // check for hexadecimal floating-point number
  1007. if (l > i+1 ) {
  1008. char ch = in.charAt(i+1);
  1009. if (ch == 'x' || ch == 'X' ) // possible hex string
  1010. return parseHexString(in);
  1011. }
  1012. } // look for and process decimal floating-point string
  1013. char[] digits = new char[ l ];
  1014. int nDigits= 0;
  1015. boolean decSeen = false;
  1016. int decPt = 0;
  1017. int nLeadZero = 0;
  1018. int nTrailZero= 0;
  1019. digitLoop:
  1020. while ( i < l ){
  1021. switch ( c = in.charAt( i ) ){
  1022. case '0':
  1023. if ( nDigits > 0 ){
  1024. nTrailZero += 1;
  1025. } else {
  1026. nLeadZero += 1;
  1027. }
  1028. break; // out of switch.
  1029. case '1':
  1030. case '2':
  1031. case '3':
  1032. case '4':
  1033. case '5':
  1034. case '6':
  1035. case '7':
  1036. case '8':
  1037. case '9':
  1038. while ( nTrailZero > 0 ){
  1039. digits[nDigits++] = '0';
  1040. nTrailZero -= 1;
  1041. }
  1042. digits[nDigits++] = c;
  1043. break; // out of switch.
  1044. case '.':
  1045. if ( decSeen ){
  1046. // already saw one ., this is the 2nd.
  1047. throw new NumberFormatException("multiple points");
  1048. }
  1049. decPt = i;
  1050. if ( signSeen ){
  1051. decPt -= 1;
  1052. }
  1053. decSeen = true;
  1054. break; // out of switch.
  1055. default:
  1056. break digitLoop;
  1057. }
  1058. i++;
  1059. }
  1060. /*
  1061. * At this point, we've scanned all the digits and decimal
  1062. * point we're going to see. Trim off leading and trailing
  1063. * zeros, which will just confuse us later, and adjust
  1064. * our initial decimal exponent accordingly.
  1065. * To review:
  1066. * we have seen i total characters.
  1067. * nLeadZero of them were zeros before any other digits.
  1068. * nTrailZero of them were zeros after any other digits.
  1069. * if ( decSeen ), then a . was seen after decPt characters
  1070. * ( including leading zeros which have been discarded )
  1071. * nDigits characters were neither lead nor trailing
  1072. * zeros, nor point
  1073. */
  1074. /*
  1075. * special hack: if we saw no non-zero digits, then the
  1076. * answer is zero!
  1077. * Unfortunately, we feel honor-bound to keep parsing!
  1078. */
  1079. if ( nDigits == 0 ){
  1080. digits = zero;
  1081. nDigits = 1;
  1082. if ( nLeadZero == 0 ){
  1083. // we saw NO DIGITS AT ALL,
  1084. // not even a crummy 0!
  1085. // this is not allowed.
  1086. break parseNumber; // go throw exception
  1087. }
  1088. }
  1089. /* Our initial exponent is decPt, adjusted by the number of
  1090. * discarded zeros. Or, if there was no decPt,
  1091. * then its just nDigits adjusted by discarded trailing zeros.
  1092. */
  1093. if ( decSeen ){
  1094. decExp = decPt - nLeadZero;
  1095. } else {
  1096. decExp = nDigits+nTrailZero;
  1097. }
  1098. /*
  1099. * Look for 'e' or 'E' and an optionally signed integer.
  1100. */
  1101. if ( (i < l) && (((c = in.charAt(i) )=='e') || (c == 'E') ) ){
  1102. int expSign = 1;
  1103. int expVal = 0;
  1104. int reallyBig = Integer.MAX_VALUE / 10;
  1105. boolean expOverflow = false;
  1106. switch( in.charAt(++i) ){
  1107. case '-':
  1108. expSign = -1;
  1109. //FALLTHROUGH
  1110. case '+':
  1111. i++;
  1112. }
  1113. int expAt = i;
  1114. expLoop:
  1115. while ( i < l ){
  1116. if ( expVal >= reallyBig ){
  1117. // the next character will cause integer
  1118. // overflow.
  1119. expOverflow = true;
  1120. }
  1121. switch ( c = in.charAt(i++) ){
  1122. case '0':
  1123. case '1':
  1124. case '2':
  1125. case '3':
  1126. case '4':
  1127. case '5':
  1128. case '6':
  1129. case '7':
  1130. case '8':
  1131. case '9':
  1132. expVal = expVal*10 + ( (int)c - (int)'0' );
  1133. continue;
  1134. default:
  1135. i--; // back up.
  1136. break expLoop; // stop parsing exponent.
  1137. }
  1138. }
  1139. int expLimit = bigDecimalExponent+nDigits+nTrailZero;
  1140. if ( expOverflow || ( expVal > expLimit ) ){
  1141. //
  1142. // The intent here is to end up with
  1143. // infinity or zero, as appropriate.
  1144. // The reason for yielding such a small decExponent,
  1145. // rather than something intuitive such as
  1146. // expSign*Integer.MAX_VALUE, is that this value
  1147. // is subject to further manipulation in
  1148. // doubleValue() and floatValue(), and I don't want
  1149. // it to be able to cause overflow there!
  1150. // (The only way we can get into trouble here is for
  1151. // really outrageous nDigits+nTrailZero, such as 2 billion. )
  1152. //
  1153. decExp = expSign*expLimit;
  1154. } else {
  1155. // this should not overflow, since we tested
  1156. // for expVal > (MAX+N), where N >= abs(decExp)
  1157. decExp = decExp + expSign*expVal;
  1158. }
  1159. // if we saw something not a digit ( or end of string )
  1160. // after the [Ee][+-], without seeing any digits at all
  1161. // this is certainly an error. If we saw some digits,
  1162. // but then some trailing garbage, that might be ok.
  1163. // so we just fall through in that case.
  1164. // HUMBUG
  1165. if ( i == expAt )
  1166. break parseNumber; // certainly bad
  1167. }
  1168. /*
  1169. * We parsed everything we could.
  1170. * If there are leftovers, then this is not good input!
  1171. */
  1172. if ( i < l &&
  1173. ((i != l - 1) ||
  1174. (in.charAt(i) != 'f' &&
  1175. in.charAt(i) != 'F' &&
  1176. in.charAt(i) != 'd' &&
  1177. in.charAt(i) != 'D'))) {
  1178. break parseNumber; // go throw exception
  1179. }
  1180. return new FloatingDecimal( isNegative, decExp, digits, nDigits, false );
  1181. } catch ( StringIndexOutOfBoundsException e ){ }
  1182. throw new NumberFormatException("For input string: \"" + in + "\"");
  1183. }
  1184. /*
  1185. * Take a FloatingDecimal, which we presumably just scanned in,
  1186. * and find out what its value is, as a double.
  1187. *
  1188. * AS A SIDE EFFECT, SET roundDir TO INDICATE PREFERRED
  1189. * ROUNDING DIRECTION in case the result is really destined
  1190. * for a single-precision float.
  1191. */
  1192. public strictfp double doubleValue(){
  1193. int kDigits = Math.min( nDigits, maxDecimalDigits+1 );
  1194. long lValue;
  1195. double dValue;
  1196. double rValue, tValue;
  1197. // First, check for NaN and Infinity values
  1198. if(digits == infinity || digits == notANumber) {
  1199. if(digits == notANumber)
  1200. return Double.NaN;
  1201. else
  1202. return (isNegative?Double.NEGATIVE_INFINITY:Double.POSITIVE_INFINITY);
  1203. }
  1204. else {
  1205. if (mustSetRoundDir) {
  1206. roundDir = 0;
  1207. }
  1208. /*
  1209. * convert the lead kDigits to a long integer.
  1210. */
  1211. // (special performance hack: start to do it using int)
  1212. int iValue = (int)digits[0]-(int)'0';
  1213. int iDigits = Math.min( kDigits, intDecimalDigits );
  1214. for ( int i=1; i < iDigits; i++ ){
  1215. iValue = iValue*10 + (int)digits[i]-(int)'0';
  1216. }
  1217. lValue = (long)iValue;
  1218. for ( int i=iDigits; i < kDigits; i++ ){
  1219. lValue = lValue*10L + (long)((int)digits[i]-(int)'0');
  1220. }
  1221. dValue = (double)lValue;
  1222. int exp = decExponent-kDigits;
  1223. /*
  1224. * lValue now contains a long integer with the value of
  1225. * the first kDigits digits of the number.
  1226. * dValue contains the (double) of the same.
  1227. */
  1228. if ( nDigits <= maxDecimalDigits ){
  1229. /*
  1230. * possibly an easy case.
  1231. * We know that the digits can be represented
  1232. * exactly. And if the exponent isn't too outrageous,
  1233. * the whole thing can be done with one operation,
  1234. * thus one rounding error.
  1235. * Note that all our constructors trim all leading and
  1236. * trailing zeros, so simple values (including zero)
  1237. * will always end up here
  1238. */
  1239. if (exp == 0 || dValue == 0.0)
  1240. return (isNegative)? -dValue : dValue; // small floating integer
  1241. else if ( exp >= 0 ){
  1242. if ( exp <= maxSmallTen ){
  1243. /*
  1244. * Can get the answer with one operation,
  1245. * thus one roundoff.
  1246. */
  1247. rValue = dValue * small10pow[exp];
  1248. if ( mustSetRoundDir ){
  1249. tValue = rValue / small10pow[exp];
  1250. roundDir = ( tValue == dValue ) ? 0
  1251. :( tValue < dValue ) ? 1
  1252. : -1;
  1253. }
  1254. return (isNegative)? -rValue : rValue;
  1255. }
  1256. int slop = maxDecimalDigits - kDigits;
  1257. if ( exp <= maxSmallTen+slop ){
  1258. /*
  1259. * We can multiply dValue by 10^(slop)
  1260. * and it is still "small" and exact.
  1261. * Then we can multiply by 10^(exp-slop)
  1262. * with one rounding.
  1263. */
  1264. dValue *= small10pow[slop];
  1265. rValue = dValue * small10pow[exp-slop];
  1266. if ( mustSetRoundDir ){
  1267. tValue = rValue / small10pow[exp-slop];
  1268. roundDir = ( tValue == dValue ) ? 0
  1269. :( tValue < dValue ) ? 1
  1270. : -1;
  1271. }
  1272. return (isNegative)? -rValue : rValue;
  1273. }
  1274. /*
  1275. * Else we have a hard case with a positive exp.
  1276. */
  1277. } else {
  1278. if ( exp >= -maxSmallTen ){
  1279. /*
  1280. * Can get the answer in one division.
  1281. */
  1282. rValue = dValue / small10pow[-exp];
  1283. tValue = rValue * small10pow[-exp];
  1284. if ( mustSetRoundDir ){
  1285. roundDir = ( tValue == dValue ) ? 0
  1286. :( tValue < dValue ) ? 1
  1287. : -1;
  1288. }
  1289. return (isNegative)? -rValue : rValue;
  1290. }
  1291. /*
  1292. * Else we have a hard case with a negative exp.
  1293. */
  1294. }
  1295. }
  1296. /*
  1297. * Harder cases:
  1298. * The sum of digits plus exponent is greater than
  1299. * what we think we can do with one error.
  1300. *
  1301. * Start by approximating the right answer by,
  1302. * naively, scaling by powers of 10.
  1303. */
  1304. if ( exp > 0 ){
  1305. if ( decExponent > maxDecimalExponent+1 ){
  1306. /*
  1307. * Lets face it. This is going to be
  1308. * Infinity. Cut to the chase.
  1309. */
  1310. return (isNegative)? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
  1311. }
  1312. if ( (exp&15) != 0 ){
  1313. dValue *= small10pow[exp&15];
  1314. }
  1315. if ( (exp>>=4) != 0 ){
  1316. int j;
  1317. for( j = 0; exp > 1; j++, exp>>=1 ){
  1318. if ( (exp&1)!=0)
  1319. dValue *= big10pow[j];
  1320. }
  1321. /*
  1322. * The reason for the weird exp > 1 condition
  1323. * in the above loop was so that the last multiply
  1324. * would get unrolled. We handle it here.
  1325. * It could overflow.
  1326. */
  1327. double t = dValue * big10pow[j];
  1328. if ( Double.isInfinite( t ) ){
  1329. /*
  1330. * It did overflow.
  1331. * Look more closely at the result.
  1332. * If the exponent is just one too large,
  1333. * then use the maximum finite as our estimate
  1334. * value. Else call the result infinity
  1335. * and punt it.
  1336. * ( I presume this could happen because
  1337. * rounding forces the result here to be
  1338. * an ULP or two larger than
  1339. * Double.MAX_VALUE ).
  1340. */
  1341. t = dValue / 2.0;
  1342. t *= big10pow[j];
  1343. if ( Double.isInfinite( t ) ){
  1344. return (isNegative)? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
  1345. }
  1346. t = Double.MAX_VALUE;
  1347. }
  1348. dValue = t;
  1349. }
  1350. } else if ( exp < 0 ){
  1351. exp = -exp;
  1352. if ( decExponent < minDecimalExponent-1 ){
  1353. /*
  1354. * Lets face it. This is going to be
  1355. * zero. Cut to the chase.
  1356. */
  1357. return (isNegative)? -0.0 : 0.0;
  1358. }
  1359. if ( (exp&15) != 0 ){
  1360. dValue /= small10pow[exp&15];
  1361. }
  1362. if ( (exp>>=4) != 0 ){
  1363. int j;
  1364. for( j = 0; exp > 1; j++, exp>>=1 ){
  1365. if ( (exp&1)!=0)
  1366. dValue *= tiny10pow[j];
  1367. }
  1368. /*
  1369. * The reason for the weird exp > 1 condition
  1370. * in the above loop was so that the last multiply
  1371. * would get unrolled. We handle it here.
  1372. * It could underflow.
  1373. */
  1374. double t = dValue * tiny10pow[j];
  1375. if ( t == 0.0 ){
  1376. /*
  1377. * It did underflow.
  1378. * Look more closely at the result.
  1379. * If the exponent is just one too small,
  1380. * then use the minimum finite as our estimate
  1381. * value. Else call the result 0.0
  1382. * and punt it.
  1383. * ( I presume this could happen because
  1384. * rounding forces the result here to be
  1385. * an ULP or two less than
  1386. * Double.MIN_VALUE ).
  1387. */
  1388. t = dValue * 2.0;
  1389. t *= tiny10pow[j];
  1390. if ( t == 0.0 ){
  1391. return (isNegative)? -0.0 : 0.0;
  1392. }
  1393. t = Double.MIN_VALUE;
  1394. }
  1395. dValue = t;
  1396. }
  1397. }
  1398. /*
  1399. * dValue is now approximately the result.
  1400. * The hard part is adjusting it, by comparison
  1401. * with FDBigInt arithmetic.
  1402. * Formulate the EXACT big-number result as
  1403. * bigD0 * 10^exp
  1404. */
  1405. FDBigInt bigD0 = new FDBigInt( lValue, digits, kDigits, nDigits );
  1406. exp = decExponent - nDigits;
  1407. correctionLoop:
  1408. while(true){
  1409. /* AS A SIDE EFFECT, THIS METHOD WILL SET THE INSTANCE VARIABLES
  1410. * bigIntExp and bigIntNBits
  1411. */
  1412. FDBigInt bigB = doubleToBigInt( dValue );
  1413. /*
  1414. * Scale bigD, bigB appropriately for
  1415. * big-integer operations.
  1416. * Naively, we multiply by powers of ten
  1417. * and powers of two. What we actually do
  1418. * is keep track of the powers of 5 and
  1419. * powers of 2 we would use, then factor out
  1420. * common divisors before doing the work.
  1421. */
  1422. int B2, B5; // powers of 2, 5 in bigB
  1423. int D2, D5; // powers of 2, 5 in bigD
  1424. int Ulp2; // powers of 2 in halfUlp.
  1425. if ( exp >= 0 ){
  1426. B2 = B5 = 0;
  1427. D2 = D5 = exp;
  1428. } else {
  1429. B2 = B5 = -exp;
  1430. D2 = D5 = 0;
  1431. }
  1432. if ( bigIntExp >= 0 ){
  1433. B2 += bigIntExp;
  1434. } else {
  1435. D2 -= bigIntExp;
  1436. }
  1437. Ulp2 = B2;
  1438. // shift bigB and bigD left by a number s. t.
  1439. // halfUlp is still an integer.
  1440. int hulpbias;
  1441. if ( bigIntExp+bigIntNBits <= -expBias+1 ){
  1442. // This is going to be a denormalized number
  1443. // (if not actually zero).
  1444. // half an ULP is at 2^-(expBias+expShift+1)
  1445. hulpbias = bigIntExp+ expBias + expShift;
  1446. } else {
  1447. hulpbias = expShift + 2 - bigIntNBits;
  1448. }
  1449. B2 += hulpbias;
  1450. D2 += hulpbias;
  1451. // if there are common factors of 2, we might just as well
  1452. // factor them out, as they add nothing useful.
  1453. int common2 = Math.min( B2, Math.min( D2, Ulp2 ) );
  1454. B2 -= common2;
  1455. D2 -= common2;
  1456. Ulp2 -= common2;
  1457. // do multiplications by powers of 5 and 2
  1458. bigB = multPow52( bigB, B5, B2 );
  1459. FDBigInt bigD = multPow52( new FDBigInt( bigD0 ), D5, D2 );
  1460. //
  1461. // to recap:
  1462. // bigB is the scaled-big-int version of our floating-point
  1463. // candidate.
  1464. // bigD is the scaled-big-int version of the exact value
  1465. // as we understand it.
  1466. // halfUlp is 1/2 an ulp of bigB, except for special cases
  1467. // of exact powers of 2
  1468. //
  1469. // the plan is to compare bigB with bigD, and if the difference
  1470. // is less than halfUlp, then we're satisfied. Otherwise,
  1471. // use the ratio of difference to halfUlp to calculate a fudge
  1472. // factor to add to the floating value, then go 'round again.
  1473. //
  1474. FDBigInt diff;
  1475. int cmpResult;
  1476. boolean overvalue;
  1477. if ( (cmpResult = bigB.cmp( bigD ) ) > 0 ){
  1478. overvalue = true; // our candidate is too big.
  1479. diff = bigB.sub( bigD );
  1480. if ( (bigIntNBits == 1) && (bigIntExp > -expBias+1) ){
  1481. // candidate is a normalized exact power of 2 and
  1482. // is too big. We will be subtracting.
  1483. // For our purposes, ulp is the ulp of the
  1484. // next smaller range.
  1485. Ulp2 -= 1;
  1486. if ( Ulp2 < 0 ){
  1487. // rats. Cannot de-scale ulp this far.
  1488. // must scale diff in other direction.
  1489. Ulp2 = 0;
  1490. diff.lshiftMe( 1 );
  1491. }
  1492. }
  1493. } else if ( cmpResult < 0 ){
  1494. overvalue = false; // our candidate is too small.
  1495. diff = bigD.sub( bigB );
  1496. } else {
  1497. // the candidate is exactly right!
  1498. // this happens with surprising frequency
  1499. break correctionLoop;
  1500. }
  1501. FDBigInt halfUlp = constructPow52( B5, Ulp2 );
  1502. if ( (cmpResult = diff.cmp( halfUlp ) ) < 0 ){
  1503. // difference is small.
  1504. // this is close enough
  1505. if (mustSetRoundDir) {
  1506. roundDir = overvalue ? -1 : 1;
  1507. }
  1508. break correctionLoop;
  1509. } else if ( cmpResult == 0 ){
  1510. // difference is exactly half an ULP
  1511. // round to some other value maybe, then finish
  1512. dValue += 0.5*ulp( dValue, overvalue );
  1513. // should check for bigIntNBits == 1 here??
  1514. if (mustSetRoundDir) {
  1515. roundDir = overvalue ? -1 : 1;
  1516. }
  1517. break correctionLoop;
  1518. } else {
  1519. // difference is non-trivial.
  1520. // could scale addend by ratio of difference to
  1521. // halfUlp here, if we bothered to compute that difference.
  1522. // Most of the time ( I hope ) it is about 1 anyway.
  1523. dValue += ulp( dValue, overvalue );
  1524. if ( dValue == 0.0 || dValue == Double.POSITIVE_INFINITY )
  1525. break correctionLoop; // oops. Fell off end of range.
  1526. continue; // try again.
  1527. }
  1528. }
  1529. return (isNegative)? -dValue : dValue;
  1530. }
  1531. }
  1532. /*
  1533. * Take a FloatingDecimal, which we presumably just scanned in,
  1534. * and find out what its value is, as a float.
  1535. * This is distinct from doubleValue() to avoid the extremely
  1536. * unlikely case of a double rounding error, wherein the conversion
  1537. * to double has one rounding error, and the conversion of that double
  1538. * to a float has another rounding error, IN THE WRONG DIRECTION,
  1539. * ( because of the preference to a zero low-order bit ).
  1540. */
  1541. public strictfp float floatValue(){
  1542. int kDigits = Math.min( nDigits, singleMaxDecimalDigits+1 );
  1543. int iValue;
  1544. float fValue;
  1545. // First, check for NaN and Infinity values
  1546. if(digits == infinity || digits == notANumber) {
  1547. if(digits == notANumber)
  1548. return Float.NaN;
  1549. else
  1550. return (isNegative?Float.NEGATIVE_INFINITY:Float.POSITIVE_INFINITY);
  1551. }
  1552. else {
  1553. /*
  1554. * convert the lead kDigits to an integer.
  1555. */
  1556. iValue = (int)digits[0]-(int)'0';
  1557. for ( int i=1; i < kDigits; i++ ){
  1558. iValue = iValue*10 + (int)digits[i]-(int)'0';
  1559. }
  1560. fValue = (float)iValue;
  1561. int exp = decExponent-kDigits;
  1562. /*
  1563. * iValue now contains an integer with the value of
  1564. * the first kDigits digits of the number.
  1565. * fValue contains the (float) of the same.
  1566. */
  1567. if ( nDigits <= singleMaxDecimalDigits ){
  1568. /*
  1569. * possibly an easy case.
  1570. * We know that the digits can be represented
  1571. * exactly. And if the exponent isn't too outrageous,
  1572. * the whole thing can be done with one operation,
  1573. * thus one rounding error.
  1574. * Note that all our constructors trim all leading and
  1575. * trailing zeros, so simple values (including zero)
  1576. * will always end up here.
  1577. */
  1578. if (exp == 0 || fValue == 0.0f)
  1579. return (isNegative)? -fValue : fValue; // small floating integer
  1580. else if ( exp >= 0 ){
  1581. if ( exp <= singleMaxSmallTen ){
  1582. /*
  1583. * Can get the answer with one operation,
  1584. * thus one roundoff.
  1585. */
  1586. fValue *= singleSmall10pow[exp];
  1587. return (isNegative)? -fValue : fValue;
  1588. }
  1589. int slop = singleMaxDecimalDigits - kDigits;
  1590. if ( exp <= singleMaxSmallTen+slop ){
  1591. /*
  1592. * We can multiply dValue by 10^(slop)
  1593. * and it is still "small" and exact.
  1594. * Then we can multiply by 10^(exp-slop)
  1595. * with one rounding.
  1596. */
  1597. fValue *= singleSmall10pow[slop];
  1598. fValue *= singleSmall10pow[exp-slop];
  1599. return (isNegative)? -fValue : fValue;
  1600. }
  1601. /*
  1602. * Else we have a hard case with a positive exp.
  1603. */
  1604. } else {
  1605. if ( exp >= -singleMaxSmallTen ){
  1606. /*
  1607. * Can get the answer in one division.
  1608. */
  1609. fValue /= singleSmall10pow[-exp];
  1610. return (isNegative)? -fValue : fValue;
  1611. }
  1612. /*
  1613. * Else we have a hard case with a negative exp.
  1614. */
  1615. }
  1616. } else if ( (decExponent >= nDigits) && (nDigits+decExponent <= maxDecimalDigits) ){
  1617. /*
  1618. * In double-precision, this is an exact floating integer.
  1619. * So we can compute to double, then shorten to float
  1620. * with one round, and get the right answer.
  1621. *
  1622. * First, finish accumulating digits.
  1623. * Then convert that integer to a double, multiply
  1624. * by the appropriate power of ten, and convert to float.
  1625. */
  1626. long lValue = (long)iValue;
  1627. for ( int i=kDigits; i < nDigits; i++ ){
  1628. lValue = lValue*10L + (long)((int)digits[i]-(int)'0');
  1629. }
  1630. double dValue = (double)lValue;
  1631. exp = decExponent-nDigits;
  1632. dValue *= small10pow[exp];
  1633. fValue = (float)dValue;
  1634. return (isNegative)? -fValue : fValue;
  1635. }
  1636. /*
  1637. * Harder cases:
  1638. * The sum of digits plus exponent is greater than
  1639. * what we think we can do with one error.
  1640. *
  1641. * Start by weeding out obviously out-of-range
  1642. * results, then convert to double and go to
  1643. * common hard-case code.
  1644. */
  1645. if ( decExponent > singleMaxDecimalExponent+1 ){
  1646. /*
  1647. * Lets face it. This is going to be
  1648. * Infinity. Cut to the chase.
  1649. */
  1650. return (isNegative)? Float.NEGATIVE_INFINITY : Float.POSITIVE_INFINITY;
  1651. } else if ( decExponent < singleMinDecimalExponent-1 ){
  1652. /*
  1653. * Lets face it. This is going to be
  1654. * zero. Cut to the chase.
  1655. */
  1656. return (isNegative)? -0.0f : 0.0f;
  1657. }
  1658. /*
  1659. * Here, we do 'way too much work, but throwing away
  1660. * our partial results, and going and doing the whole
  1661. * thing as double, then throwing away half the bits that computes
  1662. * when we convert back to float.
  1663. *
  1664. * The alternative is to reproduce the whole multiple-precision
  1665. * algorithm for float precision, or to try to parameterize it
  1666. * for common usage. The former will take about 400 lines of code,
  1667. * and the latter I tried without success. Thus the semi-hack
  1668. * answer here.
  1669. */
  1670. mustSetRoundDir = !fromHex;
  1671. double dValue = doubleValue();
  1672. return stickyRound( dValue );
  1673. }
  1674. }
  1675. /*
  1676. * All the positive powers of 10 that can be
  1677. * represented exactly in double/float.
  1678. */
  1679. private static final double small10pow[] = {
  1680. 1.0e0,
  1681. 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5,
  1682. 1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10,
  1683. 1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15,
  1684. 1.0e16, 1.0e17, 1.0e18, 1.0e19, 1.0e20,
  1685. 1.0e21, 1.0e22
  1686. };
  1687. private static final float singleSmall10pow[] = {
  1688. 1.0e0f,
  1689. 1.0e1f, 1.0e2f, 1.0e3f, 1.0e4f, 1.0e5f,
  1690. 1.0e6f, 1.0e7f, 1.0e8f, 1.0e9f, 1.0e10f
  1691. };
  1692. private static final double big10pow[] = {
  1693. 1e16, 1e32, 1e64, 1e128, 1e256 };
  1694. private static final double tiny10pow[] = {
  1695. 1e-16, 1e-32, 1e-64, 1e-128, 1e-256 };
  1696. private static final int maxSmallTen = small10pow.length-1;
  1697. private static final int singleMaxSmallTen = singleSmall10pow.length-1;
  1698. private static final int small5pow[] = {
  1699. 1,
  1700. 5,
  1701. 5*5,
  1702. 5*5*5,
  1703. 5*5*5*5,
  1704. 5*5*5*5*5,
  1705. 5*5*5*5*5*5,
  1706. 5*5*5*5*5*5*5,
  1707. 5*5*5*5*5*5*5*5,
  1708. 5*5*5*5*5*5*5*5*5,
  1709. 5*5*5*5*5*5*5*5*5*5,
  1710. 5*5*5*5*5*5*5*5*5*5*5,
  1711. 5*5*5*5*5*5*5*5*5*5*5*5,
  1712. 5*5*5*5*5*5*5*5*5*5*5*5*5
  1713. };
  1714. private static final long long5pow[] = {
  1715. 1L,
  1716. 5L,
  1717. 5L*5,
  1718. 5L*5*5,
  1719. 5L*5*5*5,
  1720. 5L*5*5*5*5,
  1721. 5L*5*5*5*5*5,
  1722. 5L*5*5*5*5*5*5,
  1723. 5L*5*5*5*5*5*5*5,
  1724. 5L*5*5*5*5*5*5*5*5,
  1725. 5L*5*5*5*5*5*5*5*5*5,
  1726. 5L*5*5*5*5*5*5*5*5*5*5,
  1727. 5L*5*5*5*5*5*5*5*5*5*5*5,
  1728. 5L*5*5*5*5*5*5*5*5*5*5*5*5,
  1729. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1730. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1731. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1732. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1733. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1734. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1735. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1736. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1737. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1738. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1739. 5L*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5*5,
  1740. 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,
  1741. 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,
  1742. };
  1743. // approximately ceil( log2( long5pow[i] ) )
  1744. private static final int n5bits[] = {
  1745. 0,
  1746. 3,
  1747. 5,
  1748. 7,
  1749. 10,
  1750. 12,
  1751. 14,
  1752. 17,
  1753. 19,
  1754. 21,
  1755. 24,
  1756. 26,
  1757. 28,
  1758. 31,
  1759. 33,
  1760. 35,
  1761. 38,
  1762. 40,
  1763. 42,
  1764. 45,
  1765. 47,
  1766. 49,
  1767. 52,
  1768. 54,
  1769. 56,
  1770. 59,
  1771. 61,
  1772. };
  1773. private static final char infinity[] = { 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y' };
  1774. private static final char notANumber[] = { 'N', 'a', 'N' };
  1775. private static final char zero[] = { '0', '0', '0', '0', '0', '0', '0', '0' };
  1776. /*
  1777. * Grammar is compatible with hexadecimal floating-point constants
  1778. * described in section 6.4.4.2 of the C99 specification.
  1779. */
  1780. private static Pattern hexFloatPattern = null;
  1781. private static synchronized Pattern getHexFloatPattern() {
  1782. if (hexFloatPattern == null) {
  1783. hexFloatPattern = Pattern.compile(
  1784. //1 234 56 7 8 9
  1785. "([-+])?0[xX](((\\p{XDigit}+)\\.?)|((\\p{XDigit}*)\\.(\\p{XDigit}+)))[pP]([-+])?(\\p{Digit}+)[fFdD]?"
  1786. );
  1787. }
  1788. return hexFloatPattern;
  1789. }
  1790. /*
  1791. * Convert string s to a suitable floating decimal; uses the
  1792. * double constructor and set the roundDir variable appropriately
  1793. * in case the value is later converted to a float.
  1794. */
  1795. static FloatingDecimal parseHexString(String s) {
  1796. // Verify string is a member of the hexadecimal floating-point
  1797. // string language.
  1798. Matcher m = getHexFloatPattern().matcher(s);
  1799. boolean validInput = m.matches();
  1800. if (!validInput) {
  1801. // Input does not match pattern
  1802. throw new NumberFormatException("For input string: \"" + s + "\"");
  1803. } else { // validInput
  1804. /*
  1805. * We must isolate the sign, significand, and exponent
  1806. * fields. The sign value is straightforward. Since
  1807. * floating-point numbers are stored with a normalized
  1808. * representation, the significand and exponent are
  1809. * interrelated.
  1810. *
  1811. * After extracting the sign, we normalized the
  1812. * significand as a hexadecimal value, calculating an
  1813. * exponent adjust for any shifts made during
  1814. * normalization. If the significand is zero, the
  1815. * exponent doesn't need to be examined since the output
  1816. * will be zero.
  1817. *
  1818. * Next the exponent in the input string is extracted.
  1819. * Afterwards, the significand is normalized as a *binary*
  1820. * value and the input value's normalized exponent can be
  1821. * computed. The significand bits are copied into a
  1822. * double significand; if the string has more logical bits
  1823. * than can fit in a double, the extra bits affect the
  1824. * round and sticky bits which are used to round the final
  1825. * value.
  1826. */
  1827. // Extract significand sign
  1828. String group1 = m.group(1);
  1829. double sign = (( group1 == null ) || group1.equals("+"))? 1.0 : -1.0;
  1830. // Extract Significand magnitude
  1831. /*
  1832. * Based on the form of the significand, calculate how the
  1833. * binary exponent needs to be adjusted to create a
  1834. * normalized *hexadecimal* floating-point number; that
  1835. * is, a number where there is one nonzero hex digit to
  1836. * the left of the (hexa)decimal point. Since we are
  1837. * adjusting a binary, not hexadecimal exponent, the
  1838. * exponent is adjusted by a multiple of 4.
  1839. *
  1840. * There are a number of significand scenarios to consider;
  1841. * letters are used in indicate nonzero digits:
  1842. *
  1843. * 1. 000xxxx => x.xxx normalized
  1844. * increase exponent by (number of x's - 1)*4
  1845. *
  1846. * 2. 000xxx.yyyy => x.xxyyyy normalized
  1847. * increase exponent by (number of x's - 1)*4
  1848. *
  1849. * 3. .000yyy => y.yy normalized
  1850. * decrease exponent by (number of zeros + 1)*4
  1851. *
  1852. * 4. 000.00000yyy => y.yy normalized
  1853. * decrease exponent by (number of zeros to right of point + 1)*4
  1854. *
  1855. * If the significand is exactly zero, return a properly
  1856. * signed zero.
  1857. */
  1858. String significandString =null;
  1859. int signifLength = 0;
  1860. int exponentAdjust = 0;
  1861. {
  1862. int leftDigits = 0; // number of meaningful digits to
  1863. // left of "decimal" point
  1864. // (leading zeros stripped)
  1865. int rightDigits = 0; // number of digits to right of
  1866. // "decimal" point; leading zeros
  1867. // must always be accounted for
  1868. /*
  1869. * The significand is made up of either
  1870. *
  1871. * 1. group 4 entirely (integer portion only)
  1872. *
  1873. * OR
  1874. *
  1875. * 2. the fractional portion from group 7 plus any
  1876. * (optional) integer portions from group 6.
  1877. */
  1878. String group4;
  1879. if( (group4 = m.group(4)) != null) { // Integer-only significand
  1880. // Leading zeros never matter on the integer portion
  1881. significandString = stripLeadingZeros(group4);
  1882. leftDigits = significandString.length();
  1883. }
  1884. else {
  1885. // Group 6 is the optional integer; leading zeros
  1886. // never matter on the integer portion
  1887. String group6 = stripLeadingZeros(m.group(6));
  1888. leftDigits = group6.length();
  1889. // fraction
  1890. String group7 = m.group(7);
  1891. rightDigits = group7.length();
  1892. // Turn "integer.fraction" into "integer"+"fraction"
  1893. significandString =
  1894. ((group6 == null)?"":group6) + // is the null
  1895. // check necessary?
  1896. group7;
  1897. }
  1898. significandString = stripLeadingZeros(significandString);
  1899. signifLength = significandString.length();
  1900. /*
  1901. * Adjust exponent as described above
  1902. */
  1903. if (leftDigits >= 1) { // Cases 1 and 2
  1904. exponentAdjust = 4*(leftDigits - 1);
  1905. } else { // Cases 3 and 4
  1906. exponentAdjust = -4*( rightDigits - signifLength + 1);
  1907. }
  1908. // If the significand is zero, the exponent doesn't
  1909. // matter; return a properly signed zero.
  1910. if (signifLength == 0) { // Only zeros in input
  1911. return new FloatingDecimal(sign * 0.0);
  1912. }
  1913. }
  1914. // Extract Exponent
  1915. /*
  1916. * Use an int to read in the exponent value; this should
  1917. * provide more than sufficient range for non-contrived
  1918. * inputs. If reading the exponent in as an int does
  1919. * overflow, examine the sign of the exponent and
  1920. * significand to determine what to do.
  1921. */
  1922. String group8 = m.group(8);
  1923. boolean positiveExponent = ( group8 == null ) || group8.equals("+");
  1924. long unsignedRawExponent;
  1925. try {
  1926. unsignedRawExponent = Integer.parseInt(m.group(9));
  1927. }
  1928. catch (NumberFormatException e) {
  1929. // At this point, we know the exponent is
  1930. // syntactically well-formed as a sequence of
  1931. // digits. Therefore, if an NumberFormatException
  1932. // is thrown, it must be due to overflowing int's
  1933. // range. Also, at this point, we have already
  1934. // checked for a zero significand. Thus the signs
  1935. // of the exponent and significand determine the
  1936. // final result:
  1937. //
  1938. // significand
  1939. // + -
  1940. // exponent + +infinity -infinity
  1941. // - +0.0 -0.0
  1942. return new FloatingDecimal(sign * (positiveExponent ?
  1943. Double.POSITIVE_INFINITY : 0.0));
  1944. }
  1945. long rawExponent =
  1946. (positiveExponent ? 1L : -1L) * // exponent sign
  1947. unsignedRawExponent; // exponent magnitude
  1948. // Calculate partially adjusted exponent
  1949. long exponent = rawExponent + exponentAdjust ;
  1950. // Starting copying non-zero bits into proper position in
  1951. // a long; copy explicit bit too; this will be masked
  1952. // later for normal values.
  1953. boolean round = false;
  1954. boolean sticky = false;
  1955. int bitsCopied=0;
  1956. int nextShift=0;
  1957. long significand=0L;
  1958. // First iteration is different, since we only copy
  1959. // from the leading significand bit; one more exponent
  1960. // adjust will be needed...
  1961. // IMPORTANT: make leadingDigit a long to avoid
  1962. // surprising shift semantics!
  1963. long leadingDigit = getHexDigit(significandString, 0);
  1964. /*
  1965. * Left shift the leading digit (53 - (bit position of
  1966. * leading 1 in digit)); this sets the top bit of the
  1967. * significand to 1. The nextShift value is adjusted
  1968. * to take into account the number of bit positions of
  1969. * the leadingDigit actually used. Finally, the
  1970. * exponent is adjusted to normalize the significand
  1971. * as a binary value, not just a hex value.
  1972. */
  1973. if (leadingDigit == 1) {
  1974. significand |= leadingDigit << 52;
  1975. nextShift = 52 - 4;
  1976. /* exponent += 0 */ }
  1977. else if (leadingDigit <= 3) { // [2, 3]
  1978. significand |= leadingDigit << 51;
  1979. nextShift = 52 - 5;
  1980. exponent += 1;
  1981. }
  1982. else if (leadingDigit <= 7) { // [4, 7]
  1983. significand |= leadingDigit << 50;
  1984. nextShift = 52 - 6;
  1985. exponent += 2;
  1986. }
  1987. else if (leadingDigit <= 15) { // [8, f]
  1988. significand |= leadingDigit << 49;
  1989. nextShift = 52 - 7;
  1990. exponent += 3;
  1991. } else {
  1992. throw new AssertionError("Result from digit conversion too large!");
  1993. }
  1994. // The preceding if-else could be replaced by a single
  1995. // code block based on the high-order bit set in
  1996. // leadingDigit. Given leadingOnePosition,
  1997. // significand |= leadingDigit << (SIGNIFICAND_WIDTH - leadingOnePosition);
  1998. // nextShift = 52 - (3 + leadingOnePosition);
  1999. // exponent += (leadingOnePosition-1);
  2000. /*
  2001. * Now the exponent variable is equal to the normalized
  2002. * binary exponent. Code below will make representation
  2003. * adjustments if the exponent is incremented after
  2004. * rounding (includes overflows to infinity) or if the
  2005. * result is subnormal.
  2006. */
  2007. // Copy digit into significand until the significand can't
  2008. // hold another full hex digit or there are no more input
  2009. // hex digits.
  2010. int i = 0;
  2011. for(i = 1;
  2012. i < signifLength && nextShift >= 0;
  2013. i++) {
  2014. long currentDigit = getHexDigit(significandString, i);
  2015. significand |= (currentDigit << nextShift);
  2016. nextShift-=4;
  2017. }
  2018. // After the above loop, the bulk of the string is copied.
  2019. // Now, we must copy any partial hex digits into the
  2020. // significand AND compute the round bit and start computing
  2021. // sticky bit.
  2022. if ( i < signifLength ) { // at least one hex input digit exists
  2023. long currentDigit = getHexDigit(significandString, i);
  2024. // from nextShift, figure out how many bits need
  2025. // to be copied, if any
  2026. switch(nextShift) { // must be negative
  2027. case -1:
  2028. // three bits need to be copied in; can
  2029. // set round bit
  2030. significand |= ((currentDigit & 0xEL) >> 1);
  2031. round = (currentDigit & 0x1L) != 0L;
  2032. break;
  2033. case -2:
  2034. // two bits need to be copied in; can
  2035. // set round and start sticky
  2036. significand |= ((currentDigit & 0xCL) >> 2);
  2037. round = (currentDigit &0x2L) != 0L;
  2038. sticky = (currentDigit & 0x1L) != 0;
  2039. break;
  2040. case -3:
  2041. // one bit needs to be copied in
  2042. significand |= ((currentDigit & 0x8L)>>3);
  2043. // Now set round and start sticky, if possible
  2044. round = (currentDigit &0x4L) != 0L;
  2045. sticky = (currentDigit & 0x3L) != 0;
  2046. break;
  2047. case -4:
  2048. // all bits copied into significand; set
  2049. // round and start sticky
  2050. round = ((currentDigit & 0x8L) != 0); // is top bit set?
  2051. // nonzeros in three low order bits?
  2052. sticky = (currentDigit & 0x7L) != 0;
  2053. break;
  2054. default:
  2055. throw new AssertionError("Unexpected shift distance remainder.");
  2056. // break;
  2057. }
  2058. // Round is set; sticky might be set.
  2059. // For the sticky bit, it suffices to check the
  2060. // current digit and test for any nonzero digits in
  2061. // the remaining unprocessed input.
  2062. i++;
  2063. while(i < signifLength && !sticky) {
  2064. currentDigit = getHexDigit(significandString,i);
  2065. sticky = sticky || (currentDigit != 0);
  2066. i++;
  2067. }
  2068. }
  2069. // else all of string was seen, round and sticky are
  2070. // correct as false.
  2071. // Check for overflow and update exponent accordingly.
  2072. if (exponent > DoubleConsts.MAX_EXPONENT) { // Infinite result
  2073. // overflow to properly signed infinity
  2074. return new FloatingDecimal(sign * Double.POSITIVE_INFINITY);
  2075. } else { // Finite return value
  2076. if (exponent <= DoubleConsts.MAX_EXPONENT && // (Usually) normal result
  2077. exponent >= DoubleConsts.MIN_EXPONENT) {
  2078. // The result returned in this block cannot be a
  2079. // zero or subnormal; however after the
  2080. // significand is adjusted from rounding, we could
  2081. // still overflow in infinity.
  2082. // AND exponent bits into significand; if the
  2083. // significand is incremented and overflows from
  2084. // rounding, this combination will update the
  2085. // exponent correctly, even in the case of
  2086. // Double.MAX_VALUE overflowing to infinity.
  2087. significand = (( ((long)exponent +
  2088. (long)DoubleConsts.EXP_BIAS) <<
  2089. (DoubleConsts.SIGNIFICAND_WIDTH-1))
  2090. & DoubleConsts.EXP_BIT_MASK) |
  2091. (DoubleConsts.SIGNIF_BIT_MASK & significand);
  2092. } else { // Subnormal or zero
  2093. // (exponent < DoubleConsts.MIN_EXPONENT)
  2094. if (exponent < (DoubleConsts.MIN_SUB_EXPONENT -1 )) {
  2095. // No way to round back to nonzero value
  2096. // regardless of significand if the exponent is
  2097. // less than -1075.
  2098. return new FloatingDecimal(sign * 0.0);
  2099. } else { // -1075 <= exponent <= MIN_EXPONENT -1 = -1023
  2100. /*
  2101. * Find bit position to round to; recompute
  2102. * round and sticky bits, and shift
  2103. * significand right appropriately.
  2104. */
  2105. sticky = sticky || round;
  2106. round = false;
  2107. // Number of bits of significand to preserve is
  2108. // exponent - abs_min_exp +1
  2109. // check:
  2110. // -1075 +1074 + 1 = 0
  2111. // -1023 +1074 + 1 = 52
  2112. int bitsDiscarded = 53 -
  2113. ((int)exponent - DoubleConsts.MIN_SUB_EXPONENT + 1);
  2114. assert bitsDiscarded >= 1 && bitsDiscarded <= 53;
  2115. // What to do here:
  2116. // First, isolate the new round bit
  2117. round = (significand & (1L << (bitsDiscarded -1))) != 0L;
  2118. if (bitsDiscarded > 1) {
  2119. // create mask to update sticky bits; low
  2120. // order bitsDiscarded bits should be 1
  2121. long mask = ~((~0L) << (bitsDiscarded -1));
  2122. sticky = sticky || ((significand & mask) != 0L ) ;
  2123. }
  2124. // Now, discard the bits
  2125. significand = significand >> bitsDiscarded;
  2126. significand = (( ((long)(DoubleConsts.MIN_EXPONENT -1) + // subnorm exp.
  2127. (long)DoubleConsts.EXP_BIAS) <<
  2128. (DoubleConsts.SIGNIFICAND_WIDTH-1))
  2129. & DoubleConsts.EXP_BIT_MASK) |
  2130. (DoubleConsts.SIGNIF_BIT_MASK & significand);
  2131. }
  2132. }
  2133. // The significand variable now contains the currently
  2134. // appropriate exponent bits too.
  2135. /*
  2136. * Determine if significand should be incremented;
  2137. * making this determination depends on the least
  2138. * significant bit and the round and sticky bits.
  2139. *
  2140. * Round to nearest even rounding table, adapted from
  2141. * table 4.7 in "Computer Arithmetic" by IsraelKoren.
  2142. * The digit to the left of the "decimal" point is the
  2143. * least significant bit, the digits to the right of
  2144. * the point are the round and sticky bits
  2145. *
  2146. * Number Round(x)
  2147. * x0.00 x0.
  2148. * x0.01 x0.
  2149. * x0.10 x0.
  2150. * x0.11 x1. = x0. +1
  2151. * x1.00 x1.
  2152. * x1.01 x1.
  2153. * x1.10 x1. + 1
  2154. * x1.11 x1. + 1
  2155. */
  2156. boolean incremented = false;
  2157. boolean leastZero = ((significand & 1L) == 0L);
  2158. if( ( leastZero && round && sticky ) ||
  2159. ((!leastZero) && round )) {
  2160. incremented = true;
  2161. significand++;
  2162. }
  2163. FloatingDecimal fd = new FloatingDecimal(FpUtils.rawCopySign(
  2164. Double.longBitsToDouble(significand),
  2165. sign));
  2166. /*
  2167. * Set roundingDir variable field of fd properly so
  2168. * that the input string can be properly rounded to a
  2169. * float value. There are two cases to consider:
  2170. *
  2171. * 1. rounding to double discards sticky bit
  2172. * information that would change the result of a float
  2173. * rounding (near halfway case between two floats)
  2174. *
  2175. * 2. rounding to double rounds up when rounding up
  2176. * would not occur when rounding to float.
  2177. *
  2178. * For former case only needs to be considered when
  2179. * the bits rounded away when casting to float are all
  2180. * zero; otherwise, float round bit is properly set
  2181. * and sticky will already be true.
  2182. *
  2183. * The lower exponent bound for the code below is the
  2184. * minimum (normalized) subnormal exponent - 1 since a
  2185. * value with that exponent can round up to the
  2186. * minimum subnormal value and the sticky bit
  2187. * information must be preserved (i.e. case 1).
  2188. */
  2189. if ((exponent >= FloatConsts.MIN_SUB_EXPONENT-1) &&
  2190. (exponent <= FloatConsts.MAX_EXPONENT ) ){
  2191. // Outside above exponent range, the float value
  2192. // will be zero or infinity.
  2193. /*
  2194. * If the low-order 28 bits of a rounded double
  2195. * significand are 0, the double could be a
  2196. * half-way case for a rounding to float. If the
  2197. * double value is a half-way case, the double
  2198. * significand may have to be modified to round
  2199. * the the right float value (see the stickyRound
  2200. * method). If the rounding to double has lost
  2201. * what would be float sticky bit information, the
  2202. * double significand must be incremented. If the
  2203. * double value's significand was itself
  2204. * incremented, the float value may end up too
  2205. * large so the increment should be undone.
  2206. */
  2207. if ((significand & 0xfffffffL) == 0x0L) {
  2208. // For negative values, the sign of the
  2209. // roundDir is the same as for positive values
  2210. // since adding 1 increasing the significand's
  2211. // magnitude and subtracting 1 decreases the
  2212. // significand's magnitude. If neither round
  2213. // nor sticky is true, the double value is
  2214. // exact and no adjustment is required for a
  2215. // proper float rounding.
  2216. if( round || sticky) {
  2217. if (leastZero) { // prerounding lsb is 0
  2218. // If round and sticky were both true,
  2219. // and the least significant
  2220. // significand bit were 0, the rounded
  2221. // significand would not have its
  2222. // low-order bits be zero. Therefore,
  2223. // we only need to adjust the
  2224. // significand if round XOR sticky is
  2225. // true.
  2226. if (round ^ sticky) {
  2227. fd.roundDir = 1;
  2228. }
  2229. }
  2230. else { // prerounding lsb is 1
  2231. // If the prerounding lsb is 1 and the
  2232. // resulting significand has its
  2233. // low-order bits zero, the significand
  2234. // was incremented. Here, we undo the
  2235. // increment, which will ensure the
  2236. // right guard and sticky bits for the
  2237. // float rounding.
  2238. if (round)
  2239. fd.roundDir = -1;
  2240. }
  2241. }
  2242. }
  2243. }
  2244. fd.fromHex = true;
  2245. return fd;
  2246. }
  2247. }
  2248. }
  2249. /**
  2250. * Return <code>s</code> with any leading zeros removed.
  2251. */
  2252. static String stripLeadingZeros(String s) {
  2253. return s.replaceFirst("^0+", "");
  2254. }
  2255. /**
  2256. * Extract a hexadecimal digit from position <code>position</code>
  2257. * of string <code>s</code>.
  2258. */
  2259. static int getHexDigit(String s, int position) {
  2260. int value = Character.digit(s.charAt(position), 16);
  2261. if (value <= -1 || value >= 16) {
  2262. throw new AssertionError("Unexpected failure of digit conversion of " +
  2263. s.charAt(position));
  2264. }
  2265. return value;
  2266. }
  2267. }
  2268. /*
  2269. * A really, really simple bigint package
  2270. * tailored to the needs of floating base conversion.
  2271. */
  2272. class FDBigInt {
  2273. int nWords; // number of words used
  2274. int data[]; // value: data[0] is least significant
  2275. public FDBigInt( int v ){
  2276. nWords = 1;
  2277. data = new int[1];
  2278. data[0] = v;
  2279. }
  2280. public FDBigInt( long v ){
  2281. data = new int[2];
  2282. data[0] = (int)v;
  2283. data[1] = (int)(v>>>32);
  2284. nWords = (data[1]==0) ? 1 : 2;
  2285. }
  2286. public FDBigInt( FDBigInt other ){
  2287. data = new int[nWords = other.nWords];
  2288. System.arraycopy( other.data, 0, data, 0, nWords );
  2289. }
  2290. private FDBigInt( int [] d, int n ){
  2291. data = d;
  2292. nWords = n;
  2293. }
  2294. public FDBigInt( long seed, char digit[], int nd0, int nd ){
  2295. int n= (nd+8)/9; // estimate size needed.
  2296. if ( n < 2 ) n = 2;
  2297. data = new int[n]; // allocate enough space
  2298. data[0] = (int)seed; // starting value
  2299. data[1] = (int)(seed>>>32);
  2300. nWords = (data[1]==0) ? 1 : 2;
  2301. int i = nd0;
  2302. int limit = nd-5; // slurp digits 5 at a time.
  2303. int v;
  2304. while ( i < limit ){
  2305. int ilim = i+5;
  2306. v = (int)digit[i++]-(int)'0';
  2307. while( i <ilim ){
  2308. v = 10*v + (int)digit[i++]-(int)'0';
  2309. }
  2310. multaddMe( 100000, v); // ... where 100000 is 10^5.
  2311. }
  2312. int factor = 1;
  2313. v = 0;
  2314. while ( i < nd ){
  2315. v = 10*v + (int)digit[i++]-(int)'0';
  2316. factor *= 10;
  2317. }
  2318. if ( factor != 1 ){
  2319. multaddMe( factor, v );
  2320. }
  2321. }
  2322. /*
  2323. * Left shift by c bits.
  2324. * Shifts this in place.
  2325. */
  2326. public void
  2327. lshiftMe( int c )throws IllegalArgumentException {
  2328. if ( c <= 0 ){
  2329. if ( c == 0 )
  2330. return; // silly.
  2331. else
  2332. throw new IllegalArgumentException("negative shift count");
  2333. }
  2334. int wordcount = c>>5;
  2335. int bitcount = c & 0x1f;
  2336. int anticount = 32-bitcount;
  2337. int t[] = data;
  2338. int s[] = data;
  2339. if ( nWords+wordcount+1 > t.length ){
  2340. // reallocate.
  2341. t = new int[ nWords+wordcount+1 ];
  2342. }
  2343. int target = nWords+wordcount;
  2344. int src = nWords-1;
  2345. if ( bitcount == 0 ){
  2346. // special hack, since an anticount of 32 won't go!
  2347. System.arraycopy( s, 0, t, wordcount, nWords );
  2348. target = wordcount-1;
  2349. } else {
  2350. t[target--] = s[src]>>>anticount;
  2351. while ( src >= 1 ){
  2352. t[target--] = (s[src]<<bitcount) | (s[--src]>>>anticount);
  2353. }
  2354. t[target--] = s[src]<<bitcount;
  2355. }
  2356. while( target >= 0 ){
  2357. t[target--] = 0;
  2358. }
  2359. data = t;
  2360. nWords += wordcount + 1;
  2361. // may have constructed high-order word of 0.
  2362. // if so, trim it
  2363. while ( nWords > 1 && data[nWords-1] == 0 )
  2364. nWords--;
  2365. }
  2366. /*
  2367. * normalize this number by shifting until
  2368. * the MSB of the number is at 0x08000000.
  2369. * This is in preparation for quoRemIteration, below.
  2370. * The idea is that, to make division easier, we want the
  2371. * divisor to be "normalized" -- usually this means shifting
  2372. * the MSB into the high words sign bit. But because we know that
  2373. * the quotient will be 0 < q < 10, we would like to arrange that
  2374. * the dividend not span up into another word of precision.
  2375. * (This needs to be explained more clearly!)
  2376. */
  2377. public int
  2378. normalizeMe() throws IllegalArgumentException {
  2379. int src;
  2380. int wordcount = 0;
  2381. int bitcount = 0;
  2382. int v = 0;
  2383. for ( src= nWords-1 ; src >= 0 && (v=data[src]) == 0 ; src--){
  2384. wordcount += 1;
  2385. }
  2386. if ( src < 0 ){
  2387. // oops. Value is zero. Cannot normalize it!
  2388. throw new IllegalArgumentException("zero value");
  2389. }
  2390. /*
  2391. * In most cases, we assume that wordcount is zero. This only
  2392. * makes sense, as we try not to maintain any high-order
  2393. * words full of zeros. In fact, if there are zeros, we will
  2394. * simply SHORTEN our number at this point. Watch closely...
  2395. */
  2396. nWords -= wordcount;
  2397. /*
  2398. * Compute how far left we have to shift v s.t. its highest-
  2399. * order bit is in the right place. Then call lshiftMe to
  2400. * do the work.
  2401. */
  2402. if ( (v & 0xf0000000) != 0 ){
  2403. // will have to shift up into the next word.
  2404. // too bad.
  2405. for( bitcount = 32 ; (v & 0xf0000000) != 0 ; bitcount-- )
  2406. v >>>= 1;
  2407. } else {
  2408. while ( v <= 0x000fffff ){
  2409. // hack: byte-at-a-time shifting
  2410. v <<= 8;
  2411. bitcount += 8;
  2412. }
  2413. while ( v <= 0x07ffffff ){
  2414. v <<= 1;
  2415. bitcount += 1;
  2416. }
  2417. }
  2418. if ( bitcount != 0 )
  2419. lshiftMe( bitcount );
  2420. return bitcount;
  2421. }
  2422. /*
  2423. * Multiply a FDBigInt by an int.
  2424. * Result is a new FDBigInt.
  2425. */
  2426. public FDBigInt
  2427. mult( int iv ) {
  2428. long v = iv;
  2429. int r[];
  2430. long p;
  2431. // guess adequate size of r.
  2432. r = new int[ ( v * ((long)data[nWords-1]&0xffffffffL) > 0xfffffffL ) ? nWords+1 : nWords ];
  2433. p = 0L;
  2434. for( int i=0; i < nWords; i++ ) {
  2435. p += v * ((long)data[i]&0xffffffffL);
  2436. r[i] = (int)p;
  2437. p >>>= 32;
  2438. }
  2439. if ( p == 0L){
  2440. return new FDBigInt( r, nWords );
  2441. } else {
  2442. r[nWords] = (int)p;
  2443. return new FDBigInt( r, nWords+1 );
  2444. }
  2445. }
  2446. /*
  2447. * Multiply a FDBigInt by an int and add another int.
  2448. * Result is computed in place.
  2449. * Hope it fits!
  2450. */
  2451. public void
  2452. multaddMe( int iv, int addend ) {
  2453. long v = iv;
  2454. long p;
  2455. // unroll 0th iteration, doing addition.
  2456. p = v * ((long)data[0]&0xffffffffL) + ((long)addend&0xffffffffL);
  2457. data[0] = (int)p;
  2458. p >>>= 32;
  2459. for( int i=1; i < nWords; i++ ) {
  2460. p += v * ((long)data[i]&0xffffffffL);
  2461. data[i] = (int)p;
  2462. p >>>= 32;
  2463. }
  2464. if ( p != 0L){
  2465. data[nWords] = (int)p; // will fail noisily if illegal!
  2466. nWords++;
  2467. }
  2468. }
  2469. /*
  2470. * Multiply a FDBigInt by another FDBigInt.
  2471. * Result is a new FDBigInt.
  2472. */
  2473. public FDBigInt
  2474. mult( FDBigInt other ){
  2475. // crudely guess adequate size for r
  2476. int r[] = new int[ nWords + other.nWords ];
  2477. int i;
  2478. // I think I am promised zeros...
  2479. for( i = 0; i < this.nWords; i++ ){
  2480. long v = (long)this.data[i] & 0xffffffffL; // UNSIGNED CONVERSION
  2481. long p = 0L;
  2482. int j;
  2483. for( j = 0; j < other.nWords; j++ ){
  2484. p += ((long)r[i+j]&0xffffffffL) + v*((long)other.data[j]&0xffffffffL); // UNSIGNED CONVERSIONS ALL 'ROUND.
  2485. r[i+j] = (int)p;
  2486. p >>>= 32;
  2487. }
  2488. r[i+j] = (int)p;
  2489. }
  2490. // compute how much of r we actually needed for all that.
  2491. for ( i = r.length-1; i> 0; i--)
  2492. if ( r[i] != 0 )
  2493. break;
  2494. return new FDBigInt( r, i+1 );
  2495. }
  2496. /*
  2497. * Add one FDBigInt to another. Return a FDBigInt
  2498. */
  2499. public FDBigInt
  2500. add( FDBigInt other ){
  2501. int i;
  2502. int a[], b[];
  2503. int n, m;
  2504. long c = 0L;
  2505. // arrange such that a.nWords >= b.nWords;
  2506. // n = a.nWords, m = b.nWords
  2507. if ( this.nWords >= other.nWords ){
  2508. a = this.data;
  2509. n = this.nWords;
  2510. b = other.data;
  2511. m = other.nWords;
  2512. } else {
  2513. a = other.data;
  2514. n = other.nWords;
  2515. b = this.data;
  2516. m = this.nWords;
  2517. }
  2518. int r[] = new int[ n ];
  2519. for ( i = 0; i < n; i++ ){
  2520. c += (long)a[i] & 0xffffffffL;
  2521. if ( i < m ){
  2522. c += (long)b[i] & 0xffffffffL;
  2523. }
  2524. r[i] = (int) c;
  2525. c >>= 32; // signed shift.
  2526. }
  2527. if ( c != 0L ){
  2528. // oops -- carry out -- need longer result.
  2529. int s[] = new int[ r.length+1 ];
  2530. System.arraycopy( r, 0, s, 0, r.length );
  2531. s[i++] = (int)c;
  2532. return new FDBigInt( s, i );
  2533. }
  2534. return new FDBigInt( r, i );
  2535. }
  2536. /*
  2537. * Subtract one FDBigInt from another. Return a FDBigInt
  2538. * Assert that the result is positive.
  2539. */
  2540. public FDBigInt
  2541. sub( FDBigInt other ){
  2542. int r[] = new int[ this.nWords ];
  2543. int i;
  2544. int n = this.nWords;
  2545. int m = other.nWords;
  2546. int nzeros = 0;
  2547. long c = 0L;
  2548. for ( i = 0; i < n; i++ ){
  2549. c += (long)this.data[i] & 0xffffffffL;
  2550. if ( i < m ){
  2551. c -= (long)other.data[i] & 0xffffffffL;
  2552. }
  2553. if ( ( r[i] = (int) c ) == 0 )
  2554. nzeros++;
  2555. else
  2556. nzeros = 0;
  2557. c >>= 32; // signed shift
  2558. }
  2559. assert c == 0L : c; // borrow out of subtract
  2560. assert dataInRangeIsZero(i, m, other); // negative result of subtract
  2561. return new FDBigInt( r, n-nzeros );
  2562. }
  2563. private static boolean dataInRangeIsZero(int i, int m, FDBigInt other) {
  2564. while ( i < m )
  2565. if (other.data[i++] != 0)
  2566. return false;
  2567. return true;
  2568. }
  2569. /*
  2570. * Compare FDBigInt with another FDBigInt. Return an integer
  2571. * >0: this > other
  2572. * 0: this == other
  2573. * <0: this < other
  2574. */
  2575. public int
  2576. cmp( FDBigInt other ){
  2577. int i;
  2578. if ( this.nWords > other.nWords ){
  2579. // if any of my high-order words is non-zero,
  2580. // then the answer is evident
  2581. int j = other.nWords-1;
  2582. for ( i = this.nWords-1; i > j ; i-- )
  2583. if ( this.data[i] != 0 ) return 1;
  2584. }else if ( this.nWords < other.nWords ){
  2585. // if any of other's high-order words is non-zero,
  2586. // then the answer is evident
  2587. int j = this.nWords-1;
  2588. for ( i = other.nWords-1; i > j ; i-- )
  2589. if ( other.data[i] != 0 ) return -1;
  2590. } else{
  2591. i = this.nWords-1;
  2592. }
  2593. for ( ; i > 0 ; i-- )
  2594. if ( this.data[i] != other.data[i] )
  2595. break;
  2596. // careful! want unsigned compare!
  2597. // use brute force here.
  2598. int a = this.data[i];
  2599. int b = other.data[i];
  2600. if ( a < 0 ){
  2601. // a is really big, unsigned
  2602. if ( b < 0 ){
  2603. return a-b; // both big, negative
  2604. } else {
  2605. return 1; // b not big, answer is obvious;
  2606. }
  2607. } else {
  2608. // a is not really big
  2609. if ( b < 0 ) {
  2610. // but b is really big
  2611. return -1;
  2612. } else {
  2613. return a - b;
  2614. }
  2615. }
  2616. }
  2617. /*
  2618. * Compute
  2619. * q = (int)( this / S )
  2620. * this = 10 * ( this mod S )
  2621. * Return q.
  2622. * This is the iteration step of digit development for output.
  2623. * We assume that S has been normalized, as above, and that
  2624. * "this" has been lshift'ed accordingly.
  2625. * Also assume, of course, that the result, q, can be expressed
  2626. * as an integer, 0 <= q < 10.
  2627. */
  2628. public int
  2629. quoRemIteration( FDBigInt S )throws IllegalArgumentException {
  2630. // ensure that this and S have the same number of
  2631. // digits. If S is properly normalized and q < 10 then
  2632. // this must be so.
  2633. if ( nWords != S.nWords ){
  2634. throw new IllegalArgumentException("disparate values");
  2635. }
  2636. // estimate q the obvious way. We will usually be
  2637. // right. If not, then we're only off by a little and
  2638. // will re-add.
  2639. int n = nWords-1;
  2640. long q = ((long)data[n]&0xffffffffL) / (long)S.data[n];
  2641. long diff = 0L;
  2642. for ( int i = 0; i <= n ; i++ ){
  2643. diff += ((long)data[i]&0xffffffffL) - q*((long)S.data[i]&0xffffffffL);
  2644. data[i] = (int)diff;
  2645. diff >>= 32; // N.B. SIGNED shift.
  2646. }
  2647. if ( diff != 0L ) {
  2648. // damn, damn, damn. q is too big.
  2649. // add S back in until this turns +. This should
  2650. // not be very many times!
  2651. long sum = 0L;
  2652. while ( sum == 0L ){
  2653. sum = 0L;
  2654. for ( int i = 0; i <= n; i++ ){
  2655. sum += ((long)data[i]&0xffffffffL) + ((long)S.data[i]&0xffffffffL);
  2656. data[i] = (int) sum;
  2657. sum >>= 32; // Signed or unsigned, answer is 0 or 1
  2658. }
  2659. /*
  2660. * Originally the following line read
  2661. * "if ( sum !=0 && sum != -1 )"
  2662. * but that would be wrong, because of the
  2663. * treatment of the two values as entirely unsigned,
  2664. * it would be impossible for a carry-out to be interpreted
  2665. * as -1 -- it would have to be a single-bit carry-out, or
  2666. * +1.
  2667. */
  2668. assert sum == 0 || sum == 1 : sum; // carry out of division correction
  2669. q -= 1;
  2670. }
  2671. }
  2672. // finally, we can multiply this by 10.
  2673. // it cannot overflow, right, as the high-order word has
  2674. // at least 4 high-order zeros!
  2675. long p = 0L;
  2676. for ( int i = 0; i <= n; i++ ){
  2677. p += 10*((long)data[i]&0xffffffffL);
  2678. data[i] = (int)p;
  2679. p >>= 32; // SIGNED shift.
  2680. }
  2681. assert p == 0L : p; // Carry out of *10
  2682. return (int)q;
  2683. }
  2684. public long
  2685. longValue(){
  2686. // if this can be represented as a long, return the value
  2687. assert this.nWords > 0 : this.nWords; // longValue confused
  2688. if (this.nWords == 1)
  2689. return ((long)data[0]&0xffffffffL);
  2690. assert dataInRangeIsZero(2, this.nWords, this); // value too big
  2691. assert data[1] >= 0; // value too big
  2692. return ((long)(data[1]) << 32) | ((long)data[0]&0xffffffffL);
  2693. }
  2694. public String
  2695. toString() {
  2696. StringBuffer r = new StringBuffer(30);
  2697. r.append('[');
  2698. int i = Math.min( nWords-1, data.length-1) ;
  2699. if ( nWords > data.length ){
  2700. r.append( "("+data.length+"<"+nWords+"!)" );
  2701. }
  2702. for( ; i> 0 ; i-- ){
  2703. r.append( Integer.toHexString( data[i] ) );
  2704. r.append(' ');
  2705. }
  2706. r.append( Integer.toHexString( data[0] ) );
  2707. r.append(']');
  2708. return new String( r );
  2709. }
  2710. }