Sign in to follow this  
LilAznMVP89

How Do I Compare Fractions?

Recommended Posts

LilAznMVP89    126
How can I fix my compareTo method so that it correctly compares rational numbers. When it compares something like 8/6 to 9/3, it says 8/6 is bigger. public String compareTo (Rational op2) { String result = "Bye Bye"; System.out.println(); if (numerator > op2.getNumerator() && denominator > op2.getDenominator()) System.out.println ("First fraction is larger than second fraction. " + numerator + "/" + denominator); else if (numerator < op2.getNumerator() && denominator < op2.getDenominator()) System.out.println ("Second fraction is larger than first fraction. " + op2.getNumerator() + "/" + op2.getDenominator()); else System.out.println ("Both are equal."); return result; } Thanks :)

Share this post


Link to post
Share on other sites
tHiSiSbOb    463
If I understand your question correctly: you can just evaluate the fraction and then use simple boolean statements...


float test1=numerator1/denominator1;
float test2=numerator2/denominator2;

if(test1>test2)
{
//The first fraction is larger
}
else if(test2>test1)
{
//second fraction is larger
}
else
{
//they are equal
}




Share this post


Link to post
Share on other sites
choffstein    1090
Essentially what fruny said. Just get them over a common denominator. But basically, then you just have to compare the numerators. So multiply each numerator by the other fractions denominator, and compare.

Roight!

Share this post


Link to post
Share on other sites
TheBluMage    372
The method Fruny posted is a bit more reliable than converting to floating-point numbers. Sometimes, even if two floats/doubles should be equal, they end up being slightly different due to rounding errors. The multiplication method is probably a little faster too, since you don't have to convert four integers to floating-point, but I haven't tested it so don't hold me to that.[wink]

Share this post


Link to post
Share on other sites
LucidIon    198
Where nominators and denominators are small multiplication is more accurate, where they are large floating point is more accurate - overflow means that the multiplication method is more accurate until it is actually wrong (65535*65536 is (potentially) a large, negative number on a 32bit two's complement processor.

IEEE floating point is specified not to wraparound IIRC, which I think makes it say that two very large numbers are equal.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this