Double.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /* Double.java -- object wrapper for double
  2. Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
  3. Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.lang;
  33. import gnu.java.lang.CPStringBuilder;
  34. /**
  35. * Instances of class <code>Double</code> represent primitive
  36. * <code>double</code> values.
  37. *
  38. * Additionally, this class provides various helper functions and variables
  39. * related to doubles.
  40. *
  41. * @author Paul Fisher
  42. * @author Andrew Haley (aph@cygnus.com)
  43. * @author Eric Blake (ebb9@email.byu.edu)
  44. * @author Tom Tromey (tromey@redhat.com)
  45. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  46. * @since 1.0
  47. * @status partly updated to 1.5
  48. */
  49. public final class Double extends Number implements Comparable<Double>
  50. {
  51. /**
  52. * Compatible with JDK 1.0+.
  53. */
  54. private static final long serialVersionUID = -9172774392245257468L;
  55. /**
  56. * The maximum positive value a <code>double</code> may represent
  57. * is 1.7976931348623157e+308.
  58. */
  59. public static final double MAX_VALUE = 1.7976931348623157e+308;
  60. /**
  61. * The minimum positive value a <code>double</code> may represent
  62. * is 5e-324.
  63. */
  64. public static final double MIN_VALUE = 5e-324;
  65. /**
  66. * The value of a double representation -1.0/0.0, negative
  67. * infinity.
  68. */
  69. public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
  70. /**
  71. * The value of a double representing 1.0/0.0, positive infinity.
  72. */
  73. public static final double POSITIVE_INFINITY = 1.0 / 0.0;
  74. /**
  75. * All IEEE 754 values of NaN have the same value in Java.
  76. */
  77. public static final double NaN = 0.0 / 0.0;
  78. /**
  79. * The number of bits needed to represent a <code>double</code>.
  80. * @since 1.5
  81. */
  82. public static final int SIZE = 64;
  83. /**
  84. * The primitive type <code>double</code> is represented by this
  85. * <code>Class</code> object.
  86. * @since 1.1
  87. */
  88. public static final Class<Double> TYPE = (Class<Double>) VMClassLoader.getPrimitiveClass('D');
  89. /**
  90. * Cache representation of 0
  91. */
  92. private static final Double ZERO = new Double(0.0d);
  93. /**
  94. * Cache representation of 1
  95. */
  96. private static final Double ONE = new Double(1.0d);
  97. /**
  98. * The immutable value of this Double.
  99. *
  100. * @serial the wrapped double
  101. */
  102. private final double value;
  103. /**
  104. * Create a <code>Double</code> from the primitive <code>double</code>
  105. * specified.
  106. *
  107. * @param value the <code>double</code> argument
  108. */
  109. public Double(double value)
  110. {
  111. this.value = value;
  112. }
  113. /**
  114. * Create a <code>Double</code> from the specified <code>String</code>.
  115. * This method calls <code>Double.parseDouble()</code>.
  116. *
  117. * @param s the <code>String</code> to convert
  118. * @throws NumberFormatException if <code>s</code> cannot be parsed as a
  119. * <code>double</code>
  120. * @throws NullPointerException if <code>s</code> is null
  121. * @see #parseDouble(String)
  122. */
  123. public Double(String s)
  124. {
  125. value = parseDouble(s);
  126. }
  127. /**
  128. * Convert the <code>double</code> to a <code>String</code>.
  129. * Floating-point string representation is fairly complex: here is a
  130. * rundown of the possible values. "<code>[-]</code>" indicates that a
  131. * negative sign will be printed if the value (or exponent) is negative.
  132. * "<code>&lt;number&gt;</code>" means a string of digits ('0' to '9').
  133. * "<code>&lt;digit&gt;</code>" means a single digit ('0' to '9').<br>
  134. *
  135. * <table border=1>
  136. * <tr><th>Value of Double</th><th>String Representation</th></tr>
  137. * <tr><td>[+-] 0</td> <td><code>[-]0.0</code></td></tr>
  138. * <tr><td>Between [+-] 10<sup>-3</sup> and 10<sup>7</sup>, exclusive</td>
  139. * <td><code>[-]number.number</code></td></tr>
  140. * <tr><td>Other numeric value</td>
  141. * <td><code>[-]&lt;digit&gt;.&lt;number&gt;
  142. * E[-]&lt;number&gt;</code></td></tr>
  143. * <tr><td>[+-] infinity</td> <td><code>[-]Infinity</code></td></tr>
  144. * <tr><td>NaN</td> <td><code>NaN</code></td></tr>
  145. * </table>
  146. *
  147. * Yes, negative zero <em>is</em> a possible value. Note that there is
  148. * <em>always</em> a <code>.</code> and at least one digit printed after
  149. * it: even if the number is 3, it will be printed as <code>3.0</code>.
  150. * After the ".", all digits will be printed except trailing zeros. The
  151. * result is rounded to the shortest decimal number which will parse back
  152. * to the same double.
  153. *
  154. * <p>To create other output formats, use {@link java.text.NumberFormat}.
  155. *
  156. * @XXX specify where we are not in accord with the spec.
  157. *
  158. * @param d the <code>double</code> to convert
  159. * @return the <code>String</code> representing the <code>double</code>
  160. */
  161. public static String toString(double d)
  162. {
  163. return VMDouble.toString(d, false);
  164. }
  165. /**
  166. * Convert a double value to a hexadecimal string. This converts as
  167. * follows:
  168. * <ul>
  169. * <li> A NaN value is converted to the string "NaN".
  170. * <li> Positive infinity is converted to the string "Infinity".
  171. * <li> Negative infinity is converted to the string "-Infinity".
  172. * <li> For all other values, the first character of the result is '-'
  173. * if the value is negative. This is followed by '0x1.' if the
  174. * value is normal, and '0x0.' if the value is denormal. This is
  175. * then followed by a (lower-case) hexadecimal representation of the
  176. * mantissa, with leading zeros as required for denormal values.
  177. * The next character is a 'p', and this is followed by a decimal
  178. * representation of the unbiased exponent.
  179. * </ul>
  180. * @param d the double value
  181. * @return the hexadecimal string representation
  182. * @since 1.5
  183. */
  184. public static String toHexString(double d)
  185. {
  186. if (isNaN(d))
  187. return "NaN";
  188. if (isInfinite(d))
  189. return d < 0 ? "-Infinity" : "Infinity";
  190. long bits = doubleToLongBits(d);
  191. CPStringBuilder result = new CPStringBuilder();
  192. if (bits < 0)
  193. result.append('-');
  194. result.append("0x");
  195. final int mantissaBits = 52;
  196. final int exponentBits = 11;
  197. long mantMask = (1L << mantissaBits) - 1;
  198. long mantissa = bits & mantMask;
  199. long expMask = (1L << exponentBits) - 1;
  200. long exponent = (bits >>> mantissaBits) & expMask;
  201. result.append(exponent == 0 ? '0' : '1');
  202. result.append('.');
  203. result.append(Long.toHexString(mantissa));
  204. if (exponent == 0 && mantissa != 0)
  205. {
  206. // Treat denormal specially by inserting '0's to make
  207. // the length come out right. The constants here are
  208. // to account for things like the '0x'.
  209. int offset = 4 + ((bits < 0) ? 1 : 0);
  210. // The silly +3 is here to keep the code the same between
  211. // the Float and Double cases. In Float the value is
  212. // not a multiple of 4.
  213. int desiredLength = offset + (mantissaBits + 3) / 4;
  214. while (result.length() < desiredLength)
  215. result.insert(offset, '0');
  216. }
  217. result.append('p');
  218. if (exponent == 0 && mantissa == 0)
  219. {
  220. // Zero, so do nothing special.
  221. }
  222. else
  223. {
  224. // Apply bias.
  225. boolean denormal = exponent == 0;
  226. exponent -= (1 << (exponentBits - 1)) - 1;
  227. // Handle denormal.
  228. if (denormal)
  229. ++exponent;
  230. }
  231. result.append(Long.toString(exponent));
  232. return result.toString();
  233. }
  234. /**
  235. * Returns a <code>Double</code> object wrapping the value.
  236. * In contrast to the <code>Double</code> constructor, this method
  237. * may cache some values. It is used by boxing conversion.
  238. *
  239. * @param val the value to wrap
  240. * @return the <code>Double</code>
  241. * @since 1.5
  242. */
  243. public static Double valueOf(double val)
  244. {
  245. if ((val == 0.0) && (doubleToRawLongBits(val) == 0L))
  246. return ZERO;
  247. else if (val == 1.0)
  248. return ONE;
  249. else
  250. return new Double(val);
  251. }
  252. /**
  253. * Create a new <code>Double</code> object using the <code>String</code>.
  254. *
  255. * @param s the <code>String</code> to convert
  256. * @return the new <code>Double</code>
  257. * @throws NumberFormatException if <code>s</code> cannot be parsed as a
  258. * <code>double</code>
  259. * @throws NullPointerException if <code>s</code> is null.
  260. * @see #parseDouble(String)
  261. */
  262. public static Double valueOf(String s)
  263. {
  264. return valueOf(parseDouble(s));
  265. }
  266. /**
  267. * Parse the specified <code>String</code> as a <code>double</code>. The
  268. * extended BNF grammar is as follows:<br>
  269. * <pre>
  270. * <em>DecodableString</em>:
  271. * ( [ <code>-</code> | <code>+</code> ] <code>NaN</code> )
  272. * | ( [ <code>-</code> | <code>+</code> ] <code>Infinity</code> )
  273. * | ( [ <code>-</code> | <code>+</code> ] <em>FloatingPoint</em>
  274. * [ <code>f</code> | <code>F</code> | <code>d</code>
  275. * | <code>D</code>] )
  276. * <em>FloatingPoint</em>:
  277. * ( { <em>Digit</em> }+ [ <code>.</code> { <em>Digit</em> } ]
  278. * [ <em>Exponent</em> ] )
  279. * | ( <code>.</code> { <em>Digit</em> }+ [ <em>Exponent</em> ] )
  280. * <em>Exponent</em>:
  281. * ( ( <code>e</code> | <code>E</code> )
  282. * [ <code>-</code> | <code>+</code> ] { <em>Digit</em> }+ )
  283. * <em>Digit</em>: <em><code>'0'</code> through <code>'9'</code></em>
  284. * </pre>
  285. *
  286. * <p>NaN and infinity are special cases, to allow parsing of the output
  287. * of toString. Otherwise, the result is determined by calculating
  288. * <em>n * 10<sup>exponent</sup></em> to infinite precision, then rounding
  289. * to the nearest double. Remember that many numbers cannot be precisely
  290. * represented in floating point. In case of overflow, infinity is used,
  291. * and in case of underflow, signed zero is used. Unlike Integer.parseInt,
  292. * this does not accept Unicode digits outside the ASCII range.
  293. *
  294. * <p>If an unexpected character is found in the <code>String</code>, a
  295. * <code>NumberFormatException</code> will be thrown. Leading and trailing
  296. * 'whitespace' is ignored via <code>String.trim()</code>, but spaces
  297. * internal to the actual number are not allowed.
  298. *
  299. * <p>To parse numbers according to another format, consider using
  300. * {@link java.text.NumberFormat}.
  301. *
  302. * @XXX specify where/how we are not in accord with the spec.
  303. *
  304. * @param str the <code>String</code> to convert
  305. * @return the <code>double</code> value of <code>s</code>
  306. * @throws NumberFormatException if <code>s</code> cannot be parsed as a
  307. * <code>double</code>
  308. * @throws NullPointerException if <code>s</code> is null
  309. * @see #MIN_VALUE
  310. * @see #MAX_VALUE
  311. * @see #POSITIVE_INFINITY
  312. * @see #NEGATIVE_INFINITY
  313. * @since 1.2
  314. */
  315. public static double parseDouble(String str)
  316. {
  317. return VMDouble.parseDouble(str);
  318. }
  319. /**
  320. * Return <code>true</code> if the <code>double</code> has the same
  321. * value as <code>NaN</code>, otherwise return <code>false</code>.
  322. *
  323. * @param v the <code>double</code> to compare
  324. * @return whether the argument is <code>NaN</code>.
  325. */
  326. public static boolean isNaN(double v)
  327. {
  328. // This works since NaN != NaN is the only reflexive inequality
  329. // comparison which returns true.
  330. return v != v;
  331. }
  332. /**
  333. * Return <code>true</code> if the <code>double</code> has a value
  334. * equal to either <code>NEGATIVE_INFINITY</code> or
  335. * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
  336. *
  337. * @param v the <code>double</code> to compare
  338. * @return whether the argument is (-/+) infinity.
  339. */
  340. public static boolean isInfinite(double v)
  341. {
  342. return v == POSITIVE_INFINITY || v == NEGATIVE_INFINITY;
  343. }
  344. /**
  345. * Return <code>true</code> if the value of this <code>Double</code>
  346. * is the same as <code>NaN</code>, otherwise return <code>false</code>.
  347. *
  348. * @return whether this <code>Double</code> is <code>NaN</code>
  349. */
  350. public boolean isNaN()
  351. {
  352. return isNaN(value);
  353. }
  354. /**
  355. * Return <code>true</code> if the value of this <code>Double</code>
  356. * is the same as <code>NEGATIVE_INFINITY</code> or
  357. * <code>POSITIVE_INFINITY</code>, otherwise return <code>false</code>.
  358. *
  359. * @return whether this <code>Double</code> is (-/+) infinity
  360. */
  361. public boolean isInfinite()
  362. {
  363. return isInfinite(value);
  364. }
  365. /**
  366. * Convert the <code>double</code> value of this <code>Double</code>
  367. * to a <code>String</code>. This method calls
  368. * <code>Double.toString(double)</code> to do its dirty work.
  369. *
  370. * @return the <code>String</code> representation
  371. * @see #toString(double)
  372. */
  373. public String toString()
  374. {
  375. return toString(value);
  376. }
  377. /**
  378. * Return the value of this <code>Double</code> as a <code>byte</code>.
  379. *
  380. * @return the byte value
  381. * @since 1.1
  382. */
  383. public byte byteValue()
  384. {
  385. return (byte) value;
  386. }
  387. /**
  388. * Return the value of this <code>Double</code> as a <code>short</code>.
  389. *
  390. * @return the short value
  391. * @since 1.1
  392. */
  393. public short shortValue()
  394. {
  395. return (short) value;
  396. }
  397. /**
  398. * Return the value of this <code>Double</code> as an <code>int</code>.
  399. *
  400. * @return the int value
  401. */
  402. public int intValue()
  403. {
  404. return (int) value;
  405. }
  406. /**
  407. * Return the value of this <code>Double</code> as a <code>long</code>.
  408. *
  409. * @return the long value
  410. */
  411. public long longValue()
  412. {
  413. return (long) value;
  414. }
  415. /**
  416. * Return the value of this <code>Double</code> as a <code>float</code>.
  417. *
  418. * @return the float value
  419. */
  420. public float floatValue()
  421. {
  422. return (float) value;
  423. }
  424. /**
  425. * Return the value of this <code>Double</code>.
  426. *
  427. * @return the double value
  428. */
  429. public double doubleValue()
  430. {
  431. return value;
  432. }
  433. /**
  434. * Return a hashcode representing this Object. <code>Double</code>'s hash
  435. * code is calculated by:<br>
  436. * <code>long v = Double.doubleToLongBits(doubleValue());<br>
  437. * int hash = (int)(v^(v&gt;&gt;32))</code>.
  438. *
  439. * @return this Object's hash code
  440. * @see #doubleToLongBits(double)
  441. */
  442. public int hashCode()
  443. {
  444. long v = doubleToLongBits(value);
  445. return (int) (v ^ (v >>> 32));
  446. }
  447. /**
  448. * Returns <code>true</code> if <code>obj</code> is an instance of
  449. * <code>Double</code> and represents the same double value. Unlike comparing
  450. * two doubles with <code>==</code>, this treats two instances of
  451. * <code>Double.NaN</code> as equal, but treats <code>0.0</code> and
  452. * <code>-0.0</code> as unequal.
  453. *
  454. * <p>Note that <code>d1.equals(d2)</code> is identical to
  455. * <code>doubleToLongBits(d1.doubleValue()) ==
  456. * doubleToLongBits(d2.doubleValue())</code>.
  457. *
  458. * @param obj the object to compare
  459. * @return whether the objects are semantically equal
  460. */
  461. public boolean equals(Object obj)
  462. {
  463. if (obj instanceof Double)
  464. {
  465. double d = ((Double) obj).value;
  466. return (doubleToRawLongBits(value) == doubleToRawLongBits(d)) ||
  467. (isNaN(value) && isNaN(d));
  468. }
  469. return false;
  470. }
  471. /**
  472. * Convert the double to the IEEE 754 floating-point "double format" bit
  473. * layout. Bit 63 (the most significant) is the sign bit, bits 62-52
  474. * (masked by 0x7ff0000000000000L) represent the exponent, and bits 51-0
  475. * (masked by 0x000fffffffffffffL) are the mantissa. This function
  476. * collapses all versions of NaN to 0x7ff8000000000000L. The result of this
  477. * function can be used as the argument to
  478. * <code>Double.longBitsToDouble(long)</code> to obtain the original
  479. * <code>double</code> value.
  480. *
  481. * @param value the <code>double</code> to convert
  482. * @return the bits of the <code>double</code>
  483. * @see #longBitsToDouble(long)
  484. */
  485. public static long doubleToLongBits(double value)
  486. {
  487. if (isNaN(value))
  488. return 0x7ff8000000000000L;
  489. else
  490. return VMDouble.doubleToRawLongBits(value);
  491. }
  492. /**
  493. * Convert the double to the IEEE 754 floating-point "double format" bit
  494. * layout. Bit 63 (the most significant) is the sign bit, bits 62-52
  495. * (masked by 0x7ff0000000000000L) represent the exponent, and bits 51-0
  496. * (masked by 0x000fffffffffffffL) are the mantissa. This function
  497. * leaves NaN alone, rather than collapsing to a canonical value. The
  498. * result of this function can be used as the argument to
  499. * <code>Double.longBitsToDouble(long)</code> to obtain the original
  500. * <code>double</code> value.
  501. *
  502. * @param value the <code>double</code> to convert
  503. * @return the bits of the <code>double</code>
  504. * @see #longBitsToDouble(long)
  505. */
  506. public static long doubleToRawLongBits(double value)
  507. {
  508. return VMDouble.doubleToRawLongBits(value);
  509. }
  510. /**
  511. * Convert the argument in IEEE 754 floating-point "double format" bit
  512. * layout to the corresponding float. Bit 63 (the most significant) is the
  513. * sign bit, bits 62-52 (masked by 0x7ff0000000000000L) represent the
  514. * exponent, and bits 51-0 (masked by 0x000fffffffffffffL) are the mantissa.
  515. * This function leaves NaN alone, so that you can recover the bit pattern
  516. * with <code>Double.doubleToRawLongBits(double)</code>.
  517. *
  518. * @param bits the bits to convert
  519. * @return the <code>double</code> represented by the bits
  520. * @see #doubleToLongBits(double)
  521. * @see #doubleToRawLongBits(double)
  522. */
  523. public static double longBitsToDouble(long bits)
  524. {
  525. return VMDouble.longBitsToDouble(bits);
  526. }
  527. /**
  528. * Compare two Doubles numerically by comparing their <code>double</code>
  529. * values. The result is positive if the first is greater, negative if the
  530. * second is greater, and 0 if the two are equal. However, this special
  531. * cases NaN and signed zero as follows: NaN is considered greater than
  532. * all other doubles, including <code>POSITIVE_INFINITY</code>, and positive
  533. * zero is considered greater than negative zero.
  534. *
  535. * @param d the Double to compare
  536. * @return the comparison
  537. * @since 1.2
  538. */
  539. public int compareTo(Double d)
  540. {
  541. return compare(value, d.value);
  542. }
  543. /**
  544. * Behaves like <code>new Double(x).compareTo(new Double(y))</code>; in
  545. * other words this compares two doubles, special casing NaN and zero,
  546. * without the overhead of objects.
  547. *
  548. * @param x the first double to compare
  549. * @param y the second double to compare
  550. * @return the comparison
  551. * @since 1.4
  552. */
  553. public static int compare(double x, double y)
  554. {
  555. // handle the easy cases:
  556. if (x < y)
  557. return -1;
  558. if (x > y)
  559. return 1;
  560. // handle equality respecting that 0.0 != -0.0 (hence not using x == y):
  561. long lx = doubleToRawLongBits(x);
  562. long ly = doubleToRawLongBits(y);
  563. if (lx == ly)
  564. return 0;
  565. // handle NaNs:
  566. if (x != x)
  567. return (y != y) ? 0 : 1;
  568. else if (y != y)
  569. return -1;
  570. // handle +/- 0.0
  571. return (lx < ly) ? -1 : 1;
  572. }
  573. }