public class BigFraction
{
private BigInteger num;
private BigInteger denom;
//public static final BigFraction ZERO;
/**
*
* Creates a BigFraction with numeriator BigInteger.ZERO and denominator BigInteger.ONE
*
*/
public BigFraction()
{
//should be 0/1
num = BigInteger.ZERO;
denom = BigInteger.ONE;
}
public BigFraction(BigInteger _num, BigInteger _denom)
{
num = _num;
denom = _denom;
}
public BigFraction(BigInteger n)
{
//n/1
num = n;
denom = BigInteger.ONE;
}
public BigFraction(int _num, int _denom)
{
num = BigInteger.valueOf(_num);
denom = BigInteger.valueOf(_denom);
}
public BigFraction add(BigFraction that)
{
return new BigFraction(num.multiply(that.denom).add(that.num.multiply(denom)), denom.multiply(that.denom));
}
public BigFraction multiply(BigFraction that)
{
return new BigFraction(num.multiply(that.num), denom.multiply(that.denom));
}
public BigFraction divide(BigFraction that)
{
return new BigFraction(num.multiply(that.denom), denom.multiply(that.num));
}
public BigFraction subtract(BigFraction that)
{
return new BigFraction(num.multiply(that.denom).subtract(that.num.multiply(denom)), denom.multiply(that.denom));
}
public BigFraction abs()
{
return new BigFraction(num.abs(), denom.abs());
}
public String toString()
{
return num + "/" + denom;
}
public int compareTo(BigFraction that)
{
return new BigFraction(num, denom).compareTo(new BigFraction(that.num, that.denom));
}
public boolean equals(Object o)
{
if(new BigFraction(num,denom) == o);
return true;
}
public double floatValue()
{
//double num = num;
//double denom = denom;
return 0;
//nasty!!!!!
}
public BigFraction negate()
{
return new BigFraction(BigInteger.ZERO.subtract(num),denom);
}
public BigFraction pow(int n)
{
return new BigFraction(num.pow(n), denom.pow(n));
}
}
views:
32answers:
1
Q:
How do I get for floatValue() equals() and compareTo() to work in the following using bigintegers.
+1
A:
public boolean equals(Object o) {
if(new BigFraction(num,denom) == o);
return true;
}
The "if" doesn't actually do anything. Also, just checking if it's the same object will not give the correct result. What you could do is:
return o.num.equals(num) && o.denom.equals(o.denom);
But then you need to make sure the class is reducing 2/4 to 1/2 automatically.
public double floatValue() {
return num.floatValue() / denom.floatValue();
}
This doesn't always work of course (specially if denom is 0).
Thomas Mueller
2010-09-11 11:14:50