1. /* ====================================================================
  2. * The Apache Software License, Version 1.1
  3. *
  4. * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
  5. * reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. *
  11. * 1. Redistributions of source code must retain the above copyright
  12. * notice, this list of conditions and the following disclaimer.
  13. *
  14. * 2. Redistributions in binary form must reproduce the above copyright
  15. * notice, this list of conditions and the following disclaimer in
  16. * the documentation and/or other materials provided with the
  17. * distribution.
  18. *
  19. * 3. The end-user documentation included with the redistribution, if
  20. * any, must include the following acknowledgement:
  21. * "This product includes software developed by the
  22. * Apache Software Foundation (http://www.apache.org/)."
  23. * Alternately, this acknowledgement may appear in the software itself,
  24. * if and wherever such third-party acknowledgements normally appear.
  25. *
  26. * 4. The names "The Jakarta Project", "Commons", and "Apache Software
  27. * Foundation" must not be used to endorse or promote products derived
  28. * from this software without prior written permission. For written
  29. * permission, please contact apache@apache.org.
  30. *
  31. * 5. Products derived from this software may not be called "Apache"
  32. * nor may "Apache" appear in their names without prior written
  33. * permission of the Apache Software Foundation.
  34. *
  35. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  36. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  37. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  38. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  39. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  40. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  41. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  42. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  43. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  44. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  45. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  46. * SUCH DAMAGE.
  47. * ====================================================================
  48. *
  49. * This software consists of voluntary contributions made by many
  50. * individuals on behalf of the Apache Software Foundation. For more
  51. * information on the Apache Software Foundation, please see
  52. * <http://www.apache.org/>.
  53. */
  54. package org.apache.commons.lang.math;
  55. import java.io.Serializable;
  56. /**
  57. * <p><code>Fraction</code> is a <code>Number</code> implementation that
  58. * stores fractions accurately.</p>
  59. *
  60. * <p>This class is immutable, and interoperable with most methods that accept
  61. * a <code>Number</code>.</p>
  62. *
  63. * @author Travis Reeder
  64. * @author Stephen Colebourne
  65. * @author Tim O'Brien
  66. * @author Pete Gieser
  67. * @since 2.0
  68. * @version $Id: Fraction.java,v 1.11 2003/08/18 02:22:24 bayard Exp $
  69. */
  70. public final class Fraction extends Number implements Serializable, Comparable {
  71. /** Serialization lock, Lang version 2.0 */
  72. private static final long serialVersionUID = 65382027393090L;
  73. /**
  74. * <code>Fraction</code> representation of 0.
  75. */
  76. public static final Fraction ZERO = new Fraction(0, 1);
  77. /**
  78. * <code>Fraction</code> representation of 1.
  79. */
  80. public static final Fraction ONE = new Fraction(1, 1);
  81. /**
  82. * <code>Fraction</code> representation of 1/2.
  83. */
  84. public static final Fraction ONE_HALF = new Fraction(1, 2);
  85. /**
  86. * <code>Fraction</code> representation of 1/3.
  87. */
  88. public static final Fraction ONE_THIRD = new Fraction(1, 3);
  89. /**
  90. * <code>Fraction</code> representation of 2/3.
  91. */
  92. public static final Fraction TWO_THIRDS = new Fraction(2, 3);
  93. /**
  94. * <code>Fraction</code> representation of 1/4.
  95. */
  96. public static final Fraction ONE_QUARTER = new Fraction(1, 4);
  97. /**
  98. * <code>Fraction</code> representation of 2/4.
  99. */
  100. public static final Fraction TWO_QUARTERS = new Fraction(2, 4);
  101. /**
  102. * <code>Fraction</code> representation of 3/4.
  103. */
  104. public static final Fraction THREE_QUARTERS = new Fraction(3, 4);
  105. /**
  106. * <code>Fraction</code> representation of 1/5.
  107. */
  108. public static final Fraction ONE_FIFTH = new Fraction(1, 5);
  109. /**
  110. * <code>Fraction</code> representation of 2/5.
  111. */
  112. public static final Fraction TWO_FIFTHS = new Fraction(2, 5);
  113. /**
  114. * <code>Fraction</code> representation of 3/5.
  115. */
  116. public static final Fraction THREE_FIFTHS = new Fraction(3, 5);
  117. /**
  118. * <code>Fraction</code> representation of 4/5.
  119. */
  120. public static final Fraction FOUR_FIFTHS = new Fraction(4, 5);
  121. /**
  122. * The numerator number part of the fraction (the three in three sevenths).
  123. */
  124. private final int numerator;
  125. /**
  126. * The denominator number part of the fraction (the seven in three sevenths).
  127. */
  128. private final int denominator;
  129. /**
  130. * Cached output hashCode (class is immutable).
  131. */
  132. private transient int hashCode = 0;
  133. /**
  134. * Cached output toString (class is immutable).
  135. */
  136. private transient String toString = null;
  137. /**
  138. * Cached output toProperString (class is immutable).
  139. */
  140. private transient String toProperString = null;
  141. /**
  142. * <p>Constructs a <code>Fraction</code> instance with the 2 parts
  143. * of a fraction Y/Z.</p>
  144. *
  145. * @param numerator the numerator, for example the three in 'three sevenths'
  146. * @param denominator the denominator, for example the seven in 'three sevenths'
  147. */
  148. private Fraction(int numerator, int denominator) {
  149. super();
  150. this.numerator = numerator;
  151. this.denominator = denominator;
  152. }
  153. /**
  154. * <p>Creates a <code>Fraction</code> instance with the 2 parts
  155. * of a fraction Y/Z.</p>
  156. *
  157. * <p>Any negative signs are resolved to be on the numerator.</p>
  158. *
  159. * @param numerator the numerator, for example the three in 'three sevenths'
  160. * @param denominator the denominator, for example the seven in 'three sevenths'
  161. * @return a new fraction instance
  162. * @throws ArithmeticException if the denomiator is <code>zero</code>
  163. */
  164. public static Fraction getFraction(int numerator, int denominator) {
  165. if (denominator == 0) {
  166. throw new ArithmeticException("The denominator must not be zero");
  167. }
  168. if (denominator < 0) {
  169. numerator = -numerator;
  170. denominator = -denominator;
  171. }
  172. return new Fraction(numerator, denominator);
  173. }
  174. /**
  175. * <p>Creates a <code>Fraction</code> instance with the 3 parts
  176. * of a fraction X Y/Z.</p>
  177. *
  178. * <p>The negative sign must be passed in on the whole number part.</p>
  179. *
  180. * @param whole the whole number, for example the one in 'one and three sevenths'
  181. * @param numerator the numerator, for example the three in 'one and three sevenths'
  182. * @param denominator the denominator, for example the seven in 'one and three sevenths'
  183. * @return a new fraction instance
  184. * @throws ArithmeticException if the denomiator is <code>zero</code>
  185. * @throws ArithmeticException if the denomiator is negative
  186. * @throws ArithmeticException if the numerator is negative
  187. * @throws ArithmeticException if the resulting numerator exceeds
  188. * <code>Integer.MAX_VALUE</code>
  189. */
  190. public static Fraction getFraction(int whole, int numerator, int denominator) {
  191. if (denominator == 0) {
  192. throw new ArithmeticException("The denominator must not be zero");
  193. }
  194. if (denominator < 0) {
  195. throw new ArithmeticException("The denominator must not be negative");
  196. }
  197. if (numerator < 0) {
  198. throw new ArithmeticException("The numerator must not be negative");
  199. }
  200. double numeratorValue = 0;
  201. if (whole < 0) {
  202. numeratorValue = (double) whole * denominator - numerator;
  203. } else {
  204. numeratorValue = (double) whole * denominator + numerator;
  205. }
  206. if (Math.abs(numeratorValue) > Integer.MAX_VALUE) {
  207. throw new ArithmeticException("Numerator too large to represent as an Integer.");
  208. }
  209. return new Fraction((int) numeratorValue, denominator);
  210. }
  211. /**
  212. * <p>Creates a <code>Fraction</code> instance with the 2 parts
  213. * of a fraction Y/Z.</p>
  214. *
  215. * <p>Any negative signs are resolved to be on the numerator.</p>
  216. *
  217. * @param numerator the numerator, for example the three in 'three sevenths'
  218. * @param denominator the denominator, for example the seven in 'three sevenths'
  219. * @return a new fraction instance, with the numerator and denominator reduced
  220. * @throws ArithmeticException if the denomiator is <code>zero</code>
  221. */
  222. public static Fraction getReducedFraction(int numerator, int denominator) {
  223. if (denominator == 0) {
  224. throw new ArithmeticException("The denominator must not be zero");
  225. }
  226. if (denominator < 0) {
  227. numerator = -numerator;
  228. denominator = -denominator;
  229. }
  230. int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);
  231. return new Fraction(numerator / gcd, denominator / gcd);
  232. }
  233. /**
  234. * <p>Creates a <code>Fraction</code> instance from a <code>double</code> value.</p>
  235. *
  236. * <p>This method uses the <a href="http://archives.math.utk.edu/articles/atuyl/confrac/">
  237. * continued fraction algorithm</a>, computing a maximum of
  238. * 25 convergents and bounding the denominator by 10,000.</p>
  239. *
  240. * @param value the double value to convert
  241. * @return a new fraction instance that is close to the value
  242. * @throws ArithmeticException if <code>|value| > Integer.MAX_VALUE</code>
  243. * or <code>value = NaN</code>
  244. * @throws ArithmeticException if the calculated denomiator is <code>zero</code>
  245. * @throws ArithmeticException if the the algorithm does not converge
  246. */
  247. public static Fraction getFraction(double value) {
  248. int sign = (value < 0 ? -1 : 1);
  249. value = Math.abs(value);
  250. if (value > Integer.MAX_VALUE || Double.isNaN(value)) {
  251. throw new ArithmeticException
  252. ("The value must not be greater than Integer.MAX_VALUE or NaN");
  253. }
  254. int wholeNumber = (int) value;
  255. value -= wholeNumber;
  256. int numer0 = 0; // the pre-previous
  257. int denom0 = 1; // the pre-previous
  258. int numer1 = 1; // the previous
  259. int denom1 = 0; // the previous
  260. int numer2 = 0; // the current, setup in calculation
  261. int denom2 = 0; // the current, setup in calculation
  262. int a1 = (int) value;
  263. int a2 = 0;
  264. double x1 = 1;
  265. double x2 = 0;
  266. double y1 = value - a1;
  267. double y2 = 0;
  268. double delta1, delta2 = Double.MAX_VALUE;
  269. double fraction;
  270. int i = 1;
  271. // System.out.println("---");
  272. do {
  273. delta1 = delta2;
  274. a2 = (int) (x1 / y1);
  275. x2 = y1;
  276. y2 = x1 - a2 * y1;
  277. numer2 = a1 * numer1 + numer0;
  278. denom2 = a1 * denom1 + denom0;
  279. fraction = (double) numer2 / (double) denom2;
  280. delta2 = Math.abs(value - fraction);
  281. // System.out.println(numer2 + " " + denom2 + " " + fraction + " " + delta2 + " " + y1);
  282. a1 = a2;
  283. x1 = x2;
  284. y1 = y2;
  285. numer0 = numer1;
  286. denom0 = denom1;
  287. numer1 = numer2;
  288. denom1 = denom2;
  289. i++;
  290. // System.out.println(">>" + delta1 +" "+ delta2+" "+(delta1 > delta2)+" "+i+" "+denom2);
  291. } while ((delta1 > delta2) && (denom2 <= 10000) && (denom2 > 0) && (i < 25));
  292. if (i == 25) {
  293. throw new ArithmeticException("Unable to convert double to fraction");
  294. }
  295. return getReducedFraction((numer0 + wholeNumber * denom0) * sign, denom0);
  296. }
  297. /**
  298. * <p>Creates a Fraction from a <code>String</code>.</p>
  299. *
  300. * <p>The formats accepted are:</p>
  301. *
  302. * <p>
  303. * <ol>
  304. * <li><code>double</code> String containing a dot</li>
  305. * <li>'X Y/Z'</li>
  306. * <li>'Y/Z'</li>
  307. * </ol>
  308. * and a .</p>
  309. *
  310. * @param str the string to parse, must not be <code>null</code>
  311. * @return the new <code>Fraction</code> instance
  312. * @throws IllegalArgumentException if the string is <code>null</code>
  313. * @throws NumberFormatException if the number format is invalid
  314. */
  315. public static Fraction getFraction(String str) {
  316. if (str == null) {
  317. throw new IllegalArgumentException("The string must not be null");
  318. }
  319. // parse double format
  320. int pos = str.indexOf('.');
  321. if (pos >= 0) {
  322. return getFraction(Double.parseDouble(str));
  323. }
  324. // parse X Y/Z format
  325. pos = str.indexOf(' ');
  326. if (pos > 0) {
  327. int whole = Integer.parseInt(str.substring(0, pos));
  328. str = str.substring(pos + 1);
  329. pos = str.indexOf('/');
  330. if (pos < 0) {
  331. throw new NumberFormatException("The fraction could not be parsed as the format X Y/Z");
  332. } else {
  333. int denom = Integer.parseInt(str.substring(pos + 1));
  334. return getFraction(
  335. Integer.parseInt(str.substring(0, pos)) + whole * denom,
  336. denom
  337. );
  338. }
  339. }
  340. // parse Y/Z format
  341. pos = str.indexOf('/');
  342. if (pos < 0) {
  343. // simple whole number
  344. return getFraction(Integer.parseInt(str), 1);
  345. } else {
  346. return getFraction(
  347. Integer.parseInt(str.substring(0, pos)),
  348. Integer.parseInt(str.substring(pos + 1))
  349. );
  350. }
  351. }
  352. // Accessors
  353. //-------------------------------------------------------------------
  354. /**
  355. * <p>Gets the numerator part of the fraction.</p>
  356. *
  357. * <p>This method may return a value greater than the denominator, an
  358. * improper fraction, such as the seven in 7/4.</p>
  359. *
  360. * @return the numerator fraction part
  361. */
  362. public int getNumerator() {
  363. return numerator;
  364. }
  365. /**
  366. * <p>Gets the denominator part of the fraction.</p>
  367. *
  368. * @return the denominator fraction part
  369. */
  370. public int getDenominator() {
  371. return denominator;
  372. }
  373. /**
  374. * <p>Gets the proper numerator, always positive.</p>
  375. *
  376. * <p>An improper fraction 7/4 can be resolved into a proper one, 1 3/4.
  377. * This method returns the 3 from the proper fraction.</p>
  378. *
  379. * <p>If the fraction is negative such as -7/4, it can be resolved into
  380. * -1 3/4, so this method returns the positive proper numerator, 3.</p>
  381. *
  382. * @return the numerator fraction part of a proper fraction, always positive
  383. */
  384. public int getProperNumerator() {
  385. return Math.abs(numerator % denominator);
  386. }
  387. /**
  388. * <p>Gets the proper whole part of the fraction.</p>
  389. *
  390. * <p>An improper fraction 7/4 can be resolved into a proper one, 1 3/4.
  391. * This method returns the 1 from the proper fraction.</p>
  392. *
  393. * <p>If the fraction is negative such as -7/4, it can be resolved into
  394. * -1 3/4, so this method returns the positive whole part -1.</p>
  395. *
  396. * @return the whole fraction part of a proper fraction, that includes the sign
  397. */
  398. public int getProperWhole() {
  399. return numerator / denominator;
  400. }
  401. // Number methods
  402. //-------------------------------------------------------------------
  403. /**
  404. * <p>Gets the fraction as an <code>int</code>. This returns the whole number
  405. * part of the fraction.</p>
  406. *
  407. * @return the whole number fraction part
  408. */
  409. public int intValue() {
  410. return numerator / denominator;
  411. }
  412. /**
  413. * <p>Gets the fraction as a <code>long</code>. This returns the whole number
  414. * part of the fraction.</p>
  415. *
  416. * @return the whole number fraction part
  417. */
  418. public long longValue() {
  419. return (long) numerator / denominator;
  420. }
  421. /**
  422. * <p>Gets the fraction as a <code>float</code>. This calculates the fraction
  423. * as the numerator divided by denominator.</p>
  424. *
  425. * @return the fraction as a <code>float</code>
  426. */
  427. public float floatValue() {
  428. return ((float) numerator) / ((float) denominator);
  429. }
  430. /**
  431. * <p>Gets the fraction as a <code>double</code>. This calculates the fraction
  432. * as the numerator divided by denominator.</p>
  433. *
  434. * @return the fraction as a <code>double</code>
  435. */
  436. public double doubleValue() {
  437. return ((double) numerator) / ((double) denominator);
  438. }
  439. // Calculations
  440. //-------------------------------------------------------------------
  441. /**
  442. * <p>Reduce the fraction to the smallest values for the numerator and
  443. * denominator, returning the result..</p>
  444. *
  445. * @return a new reduce fraction instance, or this if no simplification possible
  446. */
  447. public Fraction reduce() {
  448. int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);
  449. return Fraction.getFraction(numerator / gcd, denominator / gcd);
  450. }
  451. /**
  452. * <p>Gets a fraction that is the invert (1/fraction) of this one.</p>
  453. *
  454. * <p>The returned fraction is not reduced.</p>
  455. *
  456. * @return a new fraction instance with the numerator and denominator inverted
  457. * @throws ArithmeticException if the numerator is <code>zero</code>
  458. */
  459. public Fraction invert() {
  460. if (numerator == 0) {
  461. throw new ArithmeticException("Unable to invert a fraction with a zero numerator");
  462. }
  463. return getFraction(denominator, numerator);
  464. }
  465. /**
  466. * <p>Gets a fraction that is the negative (-fraction) of this one.</p>
  467. *
  468. * <p>The returned fraction is not reduced.</p>
  469. *
  470. * @return a new fraction instance with the opposite signed numerator
  471. */
  472. public Fraction negate() {
  473. return getFraction(-numerator, denominator);
  474. }
  475. /**
  476. * <p>Gets a fraction that is the positive equivalent of this one.</p>
  477. * <p>More precisely: <pre>(fraction >= 0 ? this : -fraction)</pre></p>
  478. *
  479. * <p>The returned fraction is not reduced.</p>
  480. *
  481. * @return <code>this</code> if it is positive, or a new positive fraction
  482. * instance with the opposite signed numerator
  483. */
  484. public Fraction abs() {
  485. if (numerator >= 0) {
  486. return this;
  487. }
  488. return getFraction(-numerator, denominator);
  489. }
  490. /**
  491. * <p>Gets a fraction that is raised to the passed in power.</p>
  492. *
  493. * <p>The returned fraction is not reduced.</p>
  494. *
  495. * @param power the power to raise the fraction to
  496. * @return <code>this</code> if the power is one, <code>ONE</code> if the power
  497. * is zero (even if the fraction equals ZERO) or a new fraction instance
  498. * raised to the appropriate power
  499. * @throws ArithmeticException if the resulting numerator or denominator exceeds
  500. * <code>Integer.MAX_VALUE</code>
  501. */
  502. public Fraction pow(int power) {
  503. if (power == 1) {
  504. return this;
  505. } else if (power == 0) {
  506. return ONE;
  507. } else {
  508. double denominatorValue = Math.pow(denominator, power);
  509. double numeratorValue = Math.pow(numerator, power);
  510. if (numeratorValue > Integer.MAX_VALUE || denominatorValue > Integer.MAX_VALUE) {
  511. throw new ArithmeticException("Integer overflow");
  512. }
  513. if (power < 0) {
  514. return getFraction((int) Math.pow(denominator, -power),
  515. (int) Math.pow(numerator, -power));
  516. }
  517. return getFraction((int) Math.pow(numerator, power),
  518. (int) Math.pow(denominator, power));
  519. }
  520. }
  521. /**
  522. * <p>Gets the greatest common divisor of two numbers.</p>
  523. *
  524. * @param number1 a positive number
  525. * @param number2 a positive number
  526. * @return the greatest common divisor, never zero
  527. */
  528. private static int greatestCommonDivisor(int number1, int number2) {
  529. int remainder = number1 % number2;
  530. while (remainder != 0) {
  531. number1 = number2;
  532. number2 = remainder;
  533. remainder = number1 % number2;
  534. }
  535. return number2;
  536. }
  537. // Arithmetic
  538. //-------------------------------------------------------------------
  539. /**
  540. * <p>Adds the value of this fraction to another, returning the result in
  541. * reduced form.</p>
  542. *
  543. * @param fraction the fraction to add, must not be <code>null</code>
  544. * @return a <code>Fraction</code> instance with the resulting values
  545. * @throws IllegalArgumentException if the fraction is <code>null</code>
  546. * @throws ArithmeticException if the resulting numerator or denominator exceeds
  547. * <code>Integer.MAX_VALUE</code>
  548. */
  549. public Fraction add(Fraction fraction) {
  550. if (fraction == null) {
  551. throw new IllegalArgumentException("The fraction must not be null");
  552. }
  553. if (numerator == 0) {
  554. return fraction;
  555. }
  556. if (fraction.numerator == 0) {
  557. return this;
  558. }
  559. // Compute lcd explicitly to limit overflow
  560. int gcd = greatestCommonDivisor(Math.abs(fraction.denominator), Math.abs(denominator));
  561. int thisResidue = denominatorgcd;
  562. int thatResidue = fraction.denominatorgcd;
  563. double denominatorValue = Math.abs((double) gcd * thisResidue * thatResidue);
  564. double numeratorValue = (double) numerator * thatResidue + fraction.numerator * thisResidue;
  565. if (Math.abs(numeratorValue) > Integer.MAX_VALUE ||
  566. Math.abs(denominatorValue) > Integer.MAX_VALUE) {
  567. throw new ArithmeticException("Integer overflow");
  568. }
  569. return Fraction.getReducedFraction((int) numeratorValue, (int) denominatorValue);
  570. }
  571. /**
  572. * <p>Subtracts the value of another fraction from the value of this one,
  573. * returning the result in reduced form.</p>
  574. *
  575. * @param fraction the fraction to subtract, must not be <code>null</code>
  576. * @return a <code>Fraction</code> instance with the resulting values
  577. * @throws IllegalArgumentException if the fraction is <code>null</code>
  578. * @throws ArithmeticException if the resulting numerator or denominator exceeds
  579. * <code>Integer.MAX_VALUE</code>
  580. */
  581. public Fraction subtract(Fraction fraction) {
  582. if (fraction == null) {
  583. throw new IllegalArgumentException("The fraction must not be null");
  584. }
  585. return add(fraction.negate());
  586. }
  587. /**
  588. * <p>Multiplies the value of this fraction by another, returning the result
  589. * in reduced form.</p>
  590. *
  591. * @param fraction the fraction to multipy by, must not be <code>null</code>
  592. * @return a <code>Fraction</code> instance with the resulting values
  593. * @throws IllegalArgumentException if the fraction is <code>null</code>
  594. * @throws ArithmeticException if the resulting numerator or denominator exceeds
  595. * <code>Integer.MAX_VALUE</code>
  596. */
  597. public Fraction multiplyBy(Fraction fraction) {
  598. if (fraction == null) {
  599. throw new IllegalArgumentException("The fraction must not be null");
  600. }
  601. if (numerator == 0 || fraction.numerator == 0) {
  602. return ZERO;
  603. }
  604. double numeratorValue = (double) numerator * fraction.numerator;
  605. double denominatorValue = (double) denominator * fraction.denominator;
  606. if (Math.abs(numeratorValue) > Integer.MAX_VALUE ||
  607. Math.abs(denominatorValue) > Integer.MAX_VALUE) {
  608. throw new ArithmeticException("Integer overflow");
  609. }
  610. return getReducedFraction((int) numeratorValue, (int) denominatorValue);
  611. }
  612. /**
  613. * <p>Divide the value of this fraction by another, returning the result
  614. * in reduced form.</p>
  615. *
  616. * @param fraction the fraction to divide by, must not be <code>null</code>
  617. * @return a <code>Fraction</code> instance with the resulting values
  618. * @throws IllegalArgumentException if the fraction is <code>null</code>
  619. * @throws ArithmeticException if the fraction to divide by is zero
  620. * @throws ArithmeticException if the resulting numerator or denominator exceeds
  621. * <code>Integer.MAX_VALUE</code>
  622. */
  623. public Fraction divideBy(Fraction fraction) {
  624. if (fraction == null) {
  625. throw new IllegalArgumentException("The fraction must not be null");
  626. }
  627. if (fraction.numerator == 0) {
  628. throw new ArithmeticException("The fraction to divide by must not be zero");
  629. }
  630. if (numerator == 0) {
  631. return ZERO;
  632. }
  633. double numeratorValue = (double) numerator * fraction.denominator;
  634. double denominatorValue = (double) denominator * fraction.numerator;
  635. if (Math.abs(numeratorValue) > Integer.MAX_VALUE ||
  636. Math.abs(denominatorValue) > Integer.MAX_VALUE) {
  637. throw new ArithmeticException("Integer overflow");
  638. }
  639. return getReducedFraction((int) numeratorValue, (int) denominatorValue);
  640. }
  641. // Basics
  642. //-------------------------------------------------------------------
  643. /**
  644. * <p>Compares this fraction to another object to test if they are equal.</p>.
  645. *
  646. * <p>To be equal, both values must be equal. Thus 2/4 is not equal to 1/2.</p>
  647. *
  648. * @param obj the reference object with which to compare
  649. * @return <code>true</code> if this object is equal
  650. */
  651. public boolean equals(Object obj) {
  652. if (obj == this) {
  653. return true;
  654. }
  655. if (obj instanceof Fraction == false) {
  656. return false;
  657. }
  658. Fraction other = (Fraction) obj;
  659. return (numerator == other.numerator &&
  660. denominator == other.denominator);
  661. }
  662. /**
  663. * <p>Gets a hashCode for the fraction.</p>
  664. *
  665. * @return a hash code value for this object
  666. */
  667. public int hashCode() {
  668. if (hashCode == 0) {
  669. hashCode = 17;
  670. hashCode = 37 * hashCode + numerator;
  671. hashCode = 37 * hashCode + denominator;
  672. }
  673. return hashCode;
  674. }
  675. /**
  676. * <p>Compares this object to another based on size.</p>
  677. *
  678. * @param object the object to compare to
  679. * @return -1 if this is less, 0 if equal, +1 if greater
  680. * @throws ClassCastException if the object is not a <code>Fraction</code>
  681. * @throws NullPointerException if the object is <code>null</code>
  682. */
  683. public int compareTo(Object object) {
  684. Fraction other = (Fraction) object;
  685. if (numerator == other.numerator && denominator == other.denominator) {
  686. return 0;
  687. }
  688. // otherwise see which is less
  689. long first = (long) numerator * (long) other.denominator;
  690. long second = (long) other.numerator * (long) denominator;
  691. if (first == second) {
  692. return 0;
  693. } else if (first < second) {
  694. return -1;
  695. } else {
  696. return 1;
  697. }
  698. }
  699. /**
  700. * <p>Gets the fraction as a <code>String</code>.</p>
  701. *
  702. * <p>The format used is '<i>numerator</i>/<i>denominator</i>' always.
  703. *
  704. * @return a <code>String</code> form of the fraction
  705. */
  706. public String toString() {
  707. if (toString == null) {
  708. toString = new StringBuffer(32)
  709. .append(numerator)
  710. .append('/')
  711. .append(denominator).toString();
  712. }
  713. return toString;
  714. }
  715. /**
  716. * <p>Gets the fraction as a proper <code>String</code> in the format X Y/Z.</p>
  717. *
  718. * <p>The format used in '<i>wholeNumber</i> <i>numerator</i>/<i>denominator</i>'.
  719. * If the whole number is zero it will be ommitted. If the numerator is zero,
  720. * only the whole number is returned.</p>
  721. *
  722. * @return a <code>String</code> form of the fraction
  723. */
  724. public String toProperString() {
  725. if (toProperString == null) {
  726. if (numerator == 0) {
  727. toProperString = "0";
  728. } else if (numerator == denominator) {
  729. toProperString = "1";
  730. } else if (Math.abs(numerator) > denominator) {
  731. int properNumerator = getProperNumerator();
  732. if (properNumerator == 0) {
  733. toProperString = Integer.toString(getProperWhole());
  734. } else {
  735. toProperString = new StringBuffer(32)
  736. .append(getProperWhole()).append(' ')
  737. .append(properNumerator).append('/')
  738. .append(denominator).toString();
  739. }
  740. } else {
  741. toProperString = new StringBuffer(32)
  742. .append(numerator).append('/')
  743. .append(denominator).toString();
  744. }
  745. }
  746. return toProperString;
  747. }
  748. }