view src/clojure/lang/Ratio.java @ 10:ef7dbbd6452c

added clojure source goodness
author Robert McIntyre <rlm@mit.edu>
date Sat, 21 Aug 2010 06:25:44 -0400
parents
children
line wrap: on
line source
1 /**
2 * Copyright (c) Rich Hickey. All rights reserved.
3 * The use and distribution terms for this software are covered by the
4 * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
5 * which can be found in the file epl-v10.html at the root of this distribution.
6 * By using this software in any fashion, you are agreeing to be bound by
7 * the terms of this license.
8 * You must not remove this notice, or any other, from this software.
9 **/
11 /* rich Mar 31, 2008 */
13 package clojure.lang;
15 import java.math.BigInteger;
16 import java.math.BigDecimal;
17 import java.math.MathContext;
19 public class Ratio extends Number implements Comparable{
20 final public BigInteger numerator;
21 final public BigInteger denominator;
23 public Ratio(BigInteger numerator, BigInteger denominator){
24 this.numerator = numerator;
25 this.denominator = denominator;
26 }
28 public boolean equals(Object arg0){
29 return arg0 != null
30 && arg0 instanceof Ratio
31 && ((Ratio) arg0).numerator.equals(numerator)
32 && ((Ratio) arg0).denominator.equals(denominator);
33 }
35 public int hashCode(){
36 return numerator.hashCode() ^ denominator.hashCode();
37 }
39 public String toString(){
40 return numerator.toString() + "/" + denominator.toString();
41 }
43 public int intValue(){
44 return (int) doubleValue();
45 }
47 public long longValue(){
48 return bigIntegerValue().longValue();
49 }
51 public float floatValue(){
52 return (float)doubleValue();
53 }
55 public double doubleValue(){
56 return decimalValue(MathContext.DECIMAL64).doubleValue();
57 }
59 public BigDecimal decimalValue(){
60 return decimalValue(MathContext.UNLIMITED);
61 }
63 public BigDecimal decimalValue(MathContext mc){
64 BigDecimal numerator = new BigDecimal(this.numerator);
65 BigDecimal denominator = new BigDecimal(this.denominator);
67 return numerator.divide(denominator, mc);
68 }
70 public BigInteger bigIntegerValue(){
71 return numerator.divide(denominator);
72 }
74 public int compareTo(Object o){
75 Number other = (Number)o;
76 return Numbers.compare(this, other);
77 }
78 }