PageRenderTime 56ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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.

Large files files are truncated, but you can click here to view the full file