Public Group

# How Do I Compare Fractions?

This topic is 4926 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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 on other sites
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 on other sites
Two fraction a/b and c/d. Compare a*d to c*b. (i.e. multiply both fractions by b*d).

##### Share on other sites
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 on other sites
put fraction in decimal form(i.e. do division put into diff. variable) before you compare it...it will be easier i believe..but then again i am a newbie

##### Share on other sites
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 on other sites
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.

• 10
• 19
• 14
• 19
• 15