473,404 Members | 2,187 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

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
Expand|Select|Wrap|Line Numbers
  1. //********************************************************************
  2. //  Rational.java       Author: Ali
  3. //  Represents one rational number with a numerator and denominator.
  4. //********************************************************************
  5.  
  6. public class Rational implements Comparable
  7. {
  8.    private int numerator, denominator;
  9.  
  10.    //-----------------------------------------------------------------
  11.    //  Sets up the rational number by ensuring a nonzero denominator
  12.    //  and making only the numerator signed.
  13.    //-----------------------------------------------------------------
  14.    public Rational (int numer, int denom)
  15.    {
  16.       if (denom == 0)
  17.          denom = 1;
  18.  
  19.       // Make the numerator "store" the sign
  20.       if (denom < 0)
  21.       {
  22.          numer = numer * -1;
  23.          denom = denom * -1;
  24.       }
  25.  
  26.       numerator = numer;
  27.       denominator = denom;
  28.  
  29.       reduce();
  30.    }
  31.  
  32.    //-----------------------------------------------------------------
  33.    //  Returns the numerator of this rational number.
  34.    //-----------------------------------------------------------------
  35.    public int getNumerator ()
  36.    {
  37.       return numerator;
  38.    }
  39.  
  40.    //-----------------------------------------------------------------
  41.    //  Returns the denominator of this rational number.
  42.    //-----------------------------------------------------------------
  43.    public int getDenominator ()
  44.    {
  45.       return denominator;
  46.    }
  47.  
  48.    //-----------------------------------------------------------------
  49.    //  Returns the reciprocal of this rational number.
  50.    //-----------------------------------------------------------------
  51.    public Rational reciprocal ()
  52.    {
  53.       return new Rational (denominator, numerator);
  54.    }
  55.  
  56.    //-----------------------------------------------------------------
  57.    //  Adds this rational number to the one passed as a parameter.
  58.    //  A common denominator is found by multiplying the individual
  59.    //  denominators.
  60.    //-----------------------------------------------------------------
  61.    public Rational add (Rational op2)
  62.    {
  63.       int commonDenominator = denominator * op2.getDenominator();
  64.       int numerator1 = numerator * op2.getDenominator();
  65.       int numerator2 = op2.getNumerator() * denominator;
  66.       int sum = numerator1 + numerator2;
  67.  
  68.       return new Rational (sum, commonDenominator);
  69.    }
  70.  
  71.    //-----------------------------------------------------------------
  72.    //  Subtracts the rational number passed as a parameter from this
  73.    //  rational number.
  74.    //-----------------------------------------------------------------
  75.    public Rational subtract (Rational op2)
  76.    {
  77.       int commonDenominator = denominator * op2.getDenominator();
  78.       int numerator1 = numerator * op2.getDenominator();
  79.       int numerator2 = op2.getNumerator() * denominator;
  80.       int difference = numerator1 - numerator2;
  81.  
  82.       return new Rational (difference, commonDenominator);
  83.    }
  84.  
  85.    //-----------------------------------------------------------------
  86.    //  Multiplies this rational number by the one passed as a
  87.    //  parameter.
  88.    //-----------------------------------------------------------------
  89.    public Rational multiply (Rational op2)
  90.    {
  91.       int numer = numerator * op2.getNumerator();
  92.       int denom = denominator * op2.getDenominator();
  93.  
  94.       return new Rational (numer, denom);
  95.    }
  96.  
  97.    //-----------------------------------------------------------------
  98.    //  Divides this rational number by the one passed as a parameter
  99.    //  by multiplying by the reciprocal of the second rational.
  100.    //-----------------------------------------------------------------
  101.    public Rational divide (Rational op2)
  102.    {
  103.       return multiply (op2.reciprocal());
  104.    }
  105.  
  106.    //-----------------------------------------------------------------
  107.    //  Determines if this rational number is equal to the one passed
  108.    //  as a parameter.  Assumes they are both reduced.
  109.    //-----------------------------------------------------------------
  110.    public boolean equals (Rational op2)
  111.    {
  112.       return ( numerator == op2.getNumerator() &&
  113.                denominator == op2.getDenominator() );
  114.    }
  115.  
  116.    //-----------------------------------------------------------------
  117.    //  Returns this rational number as a string.
  118.    //-----------------------------------------------------------------
  119.    public String toString ()
  120.    {
  121.       String result;
  122.  
  123.       if (numerator == 0)
  124.          result = "0";
  125.       else
  126.          if (denominator == 1)
  127.             result = numerator + "";
  128.          else
  129.             result = numerator + "/" + denominator;
  130.  
  131.       return result;
  132.    }
  133.  
  134.    //-----------------------------------------------------------------
  135.    //  Reduces this rational number by dividing both the numerator
  136.    //  and the denominator by their greatest common divisor.
  137.    //-----------------------------------------------------------------
  138.    private void reduce ()
  139.    {
  140.       if (numerator != 0)
  141.       {
  142.          int common = gcd (Math.abs(numerator), denominator);
  143.  
  144.          numerator = numerator / common;
  145.          denominator = denominator / common;
  146.       }
  147.    }
  148.  
  149.    //-----------------------------------------------------------------
  150.    //  Computes and returns the greatest common divisor of the two
  151.    //  positive parameters. Uses Euclid's algorithm.
  152.    //-----------------------------------------------------------------
  153.    private int gcd (int num1, int num2)
  154.    {
  155.       while (num1 != num2)
  156.          if (num1 > num2)
  157.             num1 = num1 - num2;
  158.          else
  159.             num2 = num2 - num1;
  160.  
  161.       return num1;
  162.    }
  163.  
  164.    public int compareTo(Object op2)
  165.    {
  166.        Rational input =  (Rational) op2;
  167.     double returnValue2 = numerator/denominator;
  168.        double r1  = input.getNumerator();
  169.        double r2  = input.getDenominator();
  170.        double r3 =r1/r2;
  171.        double diff = returnValue2-r3;
  172.        if(diff>0)
  173.            return 1;
  174.        else if(diff<0)
  175.            return -1;
  176.        else if(diff == 0)
  177.            return 0;
  178.     else 
  179.         return 5;
  180.  
  181.  
  182.  
  183.    }
  184. }
  185.  
Here is the driver program
Expand|Select|Wrap|Line Numbers
  1. /**
  2.  * @(#)RationDriver.java
  3.  *
  4.  *
  5.  * @author 
  6.  * @version 1.00 2008/11/19
  7.  */
  8.  
  9. public class RationDriver {
  10.  
  11.        public static void main(String[] args) {
  12.  
  13.        Rational first = new Rational(2,4);
  14.        Rational sec   = new Rational(1,2);
  15.  
  16.        int result;
  17.            result = first.compareTo(sec);
  18.        if(result >0)
  19.            System.out.println("The first fraction is greater");
  20.        else if(result < 0)
  21.            System.out.println("The first fraction is smaller");
  22.        else if(result ==0)
  23.            System.out.println("The 2 are equal");
  24.        } 
  25.     }
  26.  
  27.  
Nov 21 '08 #1
7 2253
Ganon11
3,652 Expert 2GB
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.
Nov 21 '08 #2
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!
Nov 21 '08 #3
Ganon11
3,652 Expert 2GB
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.
Nov 21 '08 #4
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
Nov 21 '08 #5
Ganon11
3,652 Expert 2GB
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.
Nov 21 '08 #6
JosAH
11,448 Expert 8TB
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
Nov 21 '08 #7
Nepomuk
3,112 Expert 2GB
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
Nov 21 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: skip | last post by:
I'm looking for a solution (or ideas about a solution) to the problem that strftime(3) and strptime(3) don't understand time increments of less than one second. Most operating systems can provide...
2
by: karp | last post by:
Lets say I have the following class in order to add two fractions, class Fraction{ public: Fractions::Fraction(int numer = 0, int denom = 1) { valeurNumerateur = numer; valeurDenominateur =...
33
by: selowitch | last post by:
I've been searching in vain for a way to present typographically correct fractions (not resorting to <sup> and <sub> tags) but have been frustrated by the fact that the glyphs for one-half,...
5
by: Steffen | last post by:
Hi, is it possible to have two fractions, which (mathematically) have the order a/b < c/d (a,b,c,d integers), but when (correctly) converted into floating point representation just have the...
2
by: Mori | last post by:
Hi, Can someone supply a code example of displaying a string with a fractional part, say 5 and 7 16ths. I cannot find an example of how to use the Encoding object (if that is what you use). ...
2
by: Just Me | last post by:
I need a numerical updown control that displays fractions. If the increment is 1/16 it would display 1/16, 1/32, 3/16, 1/4... I thought I might inherit from a NumericalUpDown control and place...
4
by: Bob | last post by:
Hi All, Was wondering if in C# there is an elegant way of displaying and or calculating fractions. The case: we have an app that measures/slices dices etc and all our internal measures and...
1
by: Semajthewise | last post by:
Here it is cleaned up a little more. Here's what this code does. It will take 2 fractions and add, subtract, multiply, or divide them. The user enters the fractions to be calculated into two...
5
by: gubbachchi | last post by:
Hi all, How to convert the fractions into decimals and vice versa in php. I have a form, where the user will enter fractions in the text boxes such as "1 1/2", "1 1/4" and so on. I need to store...
0
by: Paddy | last post by:
(From: http://paddy3118.blogspot.com/2008/09/python-fractions-issue.html) There seems to be a problem/difference in calculating with the new fractions module when comparing Python 26rc2 and 30rc1...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.