Fractions!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ALi Shaikh
    New Member
    • Sep 2007
    • 18

    Fractions!

    I'm haivng a problems with these fractions, Whenever I run it, it returns the first one is smaller when it is not. I modified this file to include the compareTo method, please help

    Class
    Code:
    //********************************************************************
    //  Rational.java       Author: Ali
    //  Represents one rational number with a numerator and denominator.
    //********************************************************************
    
    public class Rational implements Comparable
    {
       private int numerator, denominator;
    
       //-----------------------------------------------------------------
       //  Sets up the rational number by ensuring a nonzero denominator
       //  and making only the numerator signed.
       //-----------------------------------------------------------------
       public Rational (int numer, int denom)
       {
          if (denom == 0)
             denom = 1;
    
          // Make the numerator "store" the sign
          if (denom < 0)
          {
             numer = numer * -1;
             denom = denom * -1;
          }
    
          numerator = numer;
          denominator = denom;
    
          reduce();
       }
    
       //-----------------------------------------------------------------
       //  Returns the numerator of this rational number.
       //-----------------------------------------------------------------
       public int getNumerator ()
       {
          return numerator;
       }
    
       //-----------------------------------------------------------------
       //  Returns the denominator of this rational number.
       //-----------------------------------------------------------------
       public int getDenominator ()
       {
          return denominator;
       }
    
       //-----------------------------------------------------------------
       //  Returns the reciprocal of this rational number.
       //-----------------------------------------------------------------
       public Rational reciprocal ()
       {
          return new Rational (denominator, numerator);
       }
    
       //-----------------------------------------------------------------
       //  Adds this rational number to the one passed as a parameter.
       //  A common denominator is found by multiplying the individual
       //  denominators.
       //-----------------------------------------------------------------
       public Rational add (Rational op2)
       {
          int commonDenominator = denominator * op2.getDenominator();
          int numerator1 = numerator * op2.getDenominator();
          int numerator2 = op2.getNumerator() * denominator;
          int sum = numerator1 + numerator2;
    
          return new Rational (sum, commonDenominator);
       }
    
       //-----------------------------------------------------------------
       //  Subtracts the rational number passed as a parameter from this
       //  rational number.
       //-----------------------------------------------------------------
       public Rational subtract (Rational op2)
       {
          int commonDenominator = denominator * op2.getDenominator();
          int numerator1 = numerator * op2.getDenominator();
          int numerator2 = op2.getNumerator() * denominator;
          int difference = numerator1 - numerator2;
    
          return new Rational (difference, commonDenominator);
       }
    
       //-----------------------------------------------------------------
       //  Multiplies this rational number by the one passed as a
       //  parameter.
       //-----------------------------------------------------------------
       public Rational multiply (Rational op2)
       {
          int numer = numerator * op2.getNumerator();
          int denom = denominator * op2.getDenominator();
    
          return new Rational (numer, denom);
       }
    
       //-----------------------------------------------------------------
       //  Divides this rational number by the one passed as a parameter
       //  by multiplying by the reciprocal of the second rational.
       //-----------------------------------------------------------------
       public Rational divide (Rational op2)
       {
          return multiply (op2.reciprocal());
       }
    
       //-----------------------------------------------------------------
       //  Determines if this rational number is equal to the one passed
       //  as a parameter.  Assumes they are both reduced.
       //-----------------------------------------------------------------
       public boolean equals (Rational op2)
       {
          return ( numerator == op2.getNumerator() &&
                   denominator == op2.getDenominator() );
       }
    
       //-----------------------------------------------------------------
       //  Returns this rational number as a string.
       //-----------------------------------------------------------------
       public String toString ()
       {
          String result;
    
          if (numerator == 0)
             result = "0";
          else
             if (denominator == 1)
                result = numerator + "";
             else
                result = numerator + "/" + denominator;
        
          return result;
       }
    
       //-----------------------------------------------------------------
       //  Reduces this rational number by dividing both the numerator
       //  and the denominator by their greatest common divisor.
       //-----------------------------------------------------------------
       private void reduce ()
       {
          if (numerator != 0)
          {
             int common = gcd (Math.abs(numerator), denominator);
    
             numerator = numerator / common;
             denominator = denominator / common;
          }
       }
    
       //-----------------------------------------------------------------
       //  Computes and returns the greatest common divisor of the two
       //  positive parameters. Uses Euclid's algorithm.
       //-----------------------------------------------------------------
       private int gcd (int num1, int num2)
       {
          while (num1 != num2)
             if (num1 > num2)
                num1 = num1 - num2;
             else
                num2 = num2 - num1;
    
          return num1;
       }
       
       public int compareTo(Object op2)
       {
       	Rational input =  (Rational) op2;
        double returnValue2 = numerator/denominator;
       	double r1  = input.getNumerator();
       	double r2  = input.getDenominator();
       	double r3 =r1/r2;
       	double diff = returnValue2-r3;
       	if(diff>0)
       		return 1;
       	else if(diff<0)
       	    return -1;
       	else if(diff == 0)
       		return 0;
        else 
        	return 5;
       		
       		
     
       }
    }
    Here is the driver program
    Code:
    /**
     * @(#)RationDriver.java
     *
     *
     * @author 
     * @version 1.00 2008/11/19
     */
    
    public class RationDriver {
            
           public static void main(String[] args) {
           
           Rational first = new Rational(2,4);
           Rational sec   = new Rational(1,2);
           
           int result;
           	result = first.compareTo(sec);
           if(result >0)
           	System.out.println("The first fraction is greater");
           else if(result < 0)
           	System.out.println("The first fraction is smaller");
           else if(result ==0)
           	System.out.println("The 2 are equal");
           } 
        }
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    You may be running into some floating point error: instead of checking for equality with ==, try checking if the difference is within some small fraction (say, 10^-6).

    If this isn't working, maybe you are checking for/returning the wrong value? It doesn't look like this is the problem, though...

    EDIT: Just found the problem. In compareTo, you set the double returnValue2 to numerator/denominator, but numerator and denominator are both integers. The result of division with two integers is an integer. That means you're not getting a decimal, like you want. Cast one or both of the values to a double before dividing.

    Comment

    • ALi Shaikh
      New Member
      • Sep 2007
      • 18

      #3
      Thanks so much!!!!
      This will save me in AP CompSci A!!!
      I can't believe I forgot that!!, well it never came to my mind...
      Again thank you so much for helping dude!

      Comment

      • Ganon11
        Recognized Expert Specialist
        • Oct 2006
        • 3651

        #4
        Have you covered Exceptions yet? You really should not be taking care of 0-denominators by setting them to 1...an IOException (or the like) would probably be preferable.

        Comment

        • ALi Shaikh
          New Member
          • Sep 2007
          • 18

          #5
          Our teacher said that we just need to know what Exceptions are for the AP exam.
          She also said we learn how to "throw" exceptions in CompSci AB. However AB was canceled by the College Board because only 7-10 people took it in a school, so i guess I wont be learning that :(
          However we did cover exceptions and I know what you mean when you say its not right. But my teacher gave us the Rational class, we just had to modify it and write the other ones

          Comment

          • Ganon11
            Recognized Expert Specialist
            • Oct 2006
            • 3651

            #6
            OK, as long as you understand that it's a poor programming practice and, if you had to write your own Fraction class for a real-world application, you wouldn't make such a foolish move...

            I was in your shoes just two years ago, and I understand that you're studying to the exam - which is fine for now.

            When I took the exam, there were only about 4 or 5 people willing to take the AB exam, so we couldn't have a class just for AB. What we did, though, was 'apply' for the AB exam and study the extra material on our own (it's not that much - some extra data structures, sorting methods and time complexity, maybe exceptions, etc.). COnsider it, if you like the subject.

            Comment

            • JosAH
              Recognized Expert MVP
              • Mar 2007
              • 11453

              #7
              I'd leave out those doubles completely. For two fractions a/b and c/d you have
              taken care that the denominators b and d are > 0 so if a/b < c/d then ad < cb.
              See? No divisions needed and no doubles.

              kind regards,

              Jos

              Comment

              • Nepomuk
                Recognized Expert Specialist
                • Aug 2007
                • 3111

                #8
                Originally posted by ALi Shaikh
                However AB was canceled by the College Board because only 7-10 people took it in a school, so i guess I wont be learning that :(
                However we did cover exceptions and I know what you mean when you say its not right. But my teacher gave us the Rational class, we just had to modify it and write the other ones
                If you want to learn about Exceptions, you can check out my article "An Introduction to Exceptions" in the Howtos Section.

                Greetings,
                Nepomuk

                Comment

                Working...