Question

Rational Number *In Java* A rational number is one that can be expressed as the ratio...

Rational Number *In Java*

A rational number is one that can be expressed as the ratio of two integers, i.e., a number that can be expressed using a fraction whose numerator and denominator are integers. Examples of rational numbers are 1/2, 3/4 and 2/1. Rational numbers are thus no more than the fractions you've been familiar with since grade school.

Rational numbers can be negated, inverted, added, subtracted, multiplied, and divided in the usual manner:

The inverse, or reciprocal of a rational is the new rational number you get by swapping the numerator and denominator of the original. Thus, the inverse of 3/4 is 4/3.

Multiplying two rationals involves multiplying their numerators to produce the numerator of the result, and multiplying the denominators to similarly produce the new denominator.

Dividing two rationals involves taking the inverse of the divisor (the second number, i.e., the number 'doing' the dividing) and multiplying it with the dividend (the number being divided, i.e., the first number), producing the quotient. (For example, when performing re / r2, r1 is the dividend, r2 is the divisor, and the result r1/r2 is the quotient).

Adding and subtracting two rationals is a bit more involved, so we're going to take the easy way out:

Multiply the denominators to produce the new denominator(this is NOT what you learned in elementary school, where you found and used the lowest common denominator).

Multiply each numerator by the other rational's denominator, and add/subtract the two to produce the result's numerator.

Normalization of a Rational

The two rational numbers 6/8 and 3/4 actually represent the same value-- they are said to be equivalent. 6/8 is actually 3/4 multiplied by 2/2-- and since 2/2 is nothing more than 1, we have not changed the value of the represented number.

If the numerator and denominator can be evenly divided by the same number (thus leaving the value unchanged), we say the result is a simpler form of the number, and the process is known as reducing the fraction. The simplest or normal form of the fraction is one which cannot be further reduced and the process is called normalization or reducing to lowest terms.

The lowest terms of a rational number can thus be obtained by dividing the numerator and denominator by their greatest common divisor (gcd)-- i.e., the largest number that divides them both evenly. For example, given the rational number 16/20, the gcd of 16 and 20 is 4 and dividing 16 and 20 by 4 produces 4 and 5 respectively; thus the simplest form of 16/20 is 4/5.

The gcd of two numbers can be obtained recursively in the following fashion: gcd(a, b) : if b == 0 return a else return gcd(b, a%b)

Simplest forms are useful for printing, as well as various operations — addition and comparison in particular.

A Rational Class


Write a class named Rational that provides basic support for rational numbers. This support consists of the following methods:

The following constructors:

A 2-argument constructor that accepts a pair of integers corresponding to the numerator and denominator of the rational number. Thus passing in a numerator of 3 and a denominator of 4 would create an object representing the rational number 3/4. A denominator of 0 causes a RationalException to be thrown

A 1-argument constructor that accepts a single integer, which is used as the numerator of the new rational. The denominator should be set to 1. Thus, passing in 3, would result in the (integer-valued) rational 3/1.

A 0-argument constructor that initializes the rational to 0.

A copy constructor that accepts a Rational as an argument, which is used to initialize the new rational; i.e., the num of the argument Rational is assigned to the num of the new Rational (the receiver, i.e., the object referred to by this), and similarly for the denom

Rational-returning methods negate and inverse that return the negation (additive inverse) of the receiver (i.e.,the receiver multiplied by -1), and the inverse/reciprocal of the receiver respectively.

Four methods: add, sub, mul, div that perform basic arithmetic on rational numbers. These methods take a single Rational parameter corresponding to the second operand (the first operand is the receiver — the Rational operand on whom the method is being invoked) and returns a new Rational containing the result. Thus, if r1 contains 1/2 and r2 contains 1/4, then calling r1.add(r2) should return a Rational containing 6/8 (see above for how the addition should work).

Four methods addInPlace, subInPlace, mulInPlace, divInPlace that perform the same operations as the four above, but the result is placed into the left operand. Thus, if r1 contains 1/2 and r2 contains 1/4, then calling r1.addInPlace(r2) results in r1 containing 6/8. In other words, add corresponds to +, while addInPlace corresponds to +=.

A method inverse that returns the inverse (reciprocal) of the rational number.

A method negate that returns the negation (additive inverse — the value multiplied by -1) of the rational number.

A method getNumerator that returns the numerator of the rational number.

A method getDenominator that returns the numerator of the rational number.

A method compareTo that accepts another Rational and returns -1, 0, or 1 depending on whether the receiver is less-than, equal-to, or greater-than the argument (this is similar to the compareTo method of the String class. While normal form makes it easy to test for equality, you might want to give some thought as to how to check for greater-/less-than.

A boolean-returning method named equals that accepts a Rational argument and returns whether that argument and the receiver are equal.

A toString method that returns the string representation of rational number, in the form numerator/denominator. If the denominator is 0 — i.e., the number if an integer, simply print the numerator.

A private gcd method

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code:-

import java.util.*;

//class RationalException
class RationalException extends Exception
{
RationalException()
{
super("denominator is zero");
}
}

//class Rational
class Rational
{
//private members
private int num;
private int denom;
  
//private method to calculates gcd
private int gcd(int a, int b)
{
if(a==0) return b;
return gcd(b%a,a);
}
  
//0-argument constructor
public Rational()
{
num = 0;
denom = 1;
}
  
//1-argument constructor
public Rational(int n)
{
num = n;
denom = 1;
}
  
//2-argument constructor
public Rational(int n, int d) throws RationalException
{
if(d==0) throw new RationalException();
num = n;
denom = d;
}
  
//copy constructor
public Rational(Rational r)
{
this.num = r.num;
this.denom = denom;
}
  
//method to return numerator
public int getNumerator()
{
return num;
}
  
//method to return denominator
public int getDenominator()
{
return denom;
}
  
//method to inverse/reciprocal of Rational
public void inverse()
{
int t = num;
num = denom;
denom = t;
}
  
//method negate that returns the negation of the rational number
public void negate()
{
num = -num;
}
  
//method to add two Rational numbers
public Rational add(Rational fx) throws RationalException
{
int k = fx.denom * this.denom;
int j = fx.num * this.denom + fx.denom * this.num;
Rational tx = normalize(j,k);

return tx;
}
  
//method to suntract two Rational numbers
public Rational sub(Rational fx) throws RationalException
{
int k = fx.denom * this.denom;
int j = fx.denom * this.num - fx.num * this.denom;
Rational tx = normalize(j,k);

return tx;
}
  
//method to multiply two Rational numbers
public Rational mul(Rational fx) throws RationalException
{
int j = fx.num * this.num;
int k = fx.denom * this.denom;
Rational tx = normalize(j, k);
return tx;
}
  
//method to divide two Rational numbers
public Rational div(Rational fx) throws RationalException
{
int j = fx.denom * this.num;
int k = fx.num * this.denom;
Rational tx = normalize(j,k);
  
return tx;
}
  
//method to add two Rational numbers
public void addInPlace(Rational fx) throws RationalException
{
int k = fx.denom * this.denom;
int j = fx.num * this.denom + fx.denom * this.num;
Rational tx = normalize(j,k);
this.num = tx.num;
this.denom = tx.denom;
}
  
//method to suntract two Rational numbers
public void subInPlace(Rational fx) throws RationalException
{
int k = fx.denom * this.denom;
int j = fx.denom * this.num - fx.num * this.denom;
Rational tx = normalize(j,k);
this.num = tx.num;
this.denom = tx.denom;
}
  
//method to multiply two Rational numbers
public void mulInPlace(Rational fx) throws RationalException
{
int j = fx.num * this.num;
int k = fx.denom * this.denom;
Rational tx = normalize(j, k);
this.num = tx.num;
this.denom = tx.denom;
}
  
//method to divide two Rational numbers
public void divInPlace(Rational fx) throws RationalException
{
int j = fx.denom * this.num;
int k = fx.num * this.denom;
Rational tx = normalize(j,k);
this.num = tx.num;
this.denom = tx.denom;
}
  
//method compareTo that accepts another Rational and returns -1, 0, or 1
public int compareTo(Rational fx)
{
if(this.num*fx.denom == fx.num*this.denom)
return 0;
if(this.num*fx.denom > fx.num*this.denom)
return 1;
return -1;
}
  
//method equals that accepts a Rational argument and returns whether that argument and the receiver are equal
public boolean equals(Rational fx)
{
return this.num*fx.denom == fx.num*this.denom;
}

  
//method to return String format Rational number in the form a/b
public String toString()
{
if(denom!=0)
return num + "/" + denom;
return "" + num;
}
  
//method to normalization of a Rational number
private Rational normalize(int num, int denom) throws RationalException
{
int i, j, k;

j = Math.abs(num);
k = Math.abs(denom);
  
i = gcd(j, k);
  
num = num/i;
denom = denom/i;
  
if(num<0 && denom<0 ||denom<0)
{
num = -num;
denom = -denom;
}
  
Rational f = new Rational(num, denom);
  
return f;
}
}

//Driver class
class Main
{
//main method
public static void main (String[] args) throws RationalException
{
Rational f1 = new Rational(1, 2);
Rational f2 = new Rational(1, 3);
Rational f3 = f1.add(f2);
  
System.out.printf("%s + %s = %s\n", f1, f2, f3);

//Testing using menu
  
System.out.println("\nTesting using menu\n");
Scanner sc = new Scanner(System.in);
  
//read data
System.out.print("Enter numerator 1: ");
int n = sc.nextInt();
System.out.print("Enter denominator 1: ");
int d = sc.nextInt();
  
//create object
Rational a = new Rational(n, d);
  
//read data
System.out.print("Enter numerator 2: ");
n = sc.nextInt();
System.out.print("Enter denominator 2: ");
d = sc.nextInt();
  
//create object
Rational b = new Rational(n, d);
  
Rational c;
  
while(true)
{
//menu
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Multiply");
System.out.println("4. Divide");
System.out.println("5. Exit");
  
System.out.print("\nChoice: ");
int ch = sc.nextInt();
  
switch(ch)
{
case 1:
c = a.add(b);
System.out.printf("%s + %s = %s\n", a, b, c);
break;
case 2:
c = a.sub(b);
System.out.printf("%s - %s = %s\n", a, b, c);
break;
case 3:
c = a.mul(b);
System.out.printf("%s * %s = %s\n", a, b, c);
break;
case 4:
c = a.div(b);
System.out.printf("%s / %s = %s\n", a, b, c);
break;
case 5:
return;
}
}
}
}

Code Screenshots:-

Output Screenshot:-

Note: Could you please consider my effort on this work and give up vote. Thank you :)

Add a comment
Know the answer?
Add Answer to:
Rational Number *In Java* A rational number is one that can be expressed as the ratio...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • c++ Write a rational number class. A rational number is a number that can be written...

    c++ Write a rational number class. A rational number is a number that can be written as p/q where p and q are integers. The division is not carried out, only indicated. Thus you should represent rational numbers by two int values, numerator and denominator. Constructors must be present to create objects with any legal values. You should provide constructors to make objects out of pairs of int values; that is, a constructor with two int parameters. Since very int...

  • Make a new class called Rational to represent rational numbers in C++ language. Use a long...

    Make a new class called Rational to represent rational numbers in C++ language. Use a long to store each part (numerator and denominator). Be sure your main function fully test the class. 1. Create a helper function called gcd to calculate the greatest common divisor for the two given parameters. See Euclid’s algorithm (use google.com). Use this function to always store rationals in “lowest terms”. 2. Create a default, one argument and two argument constructor. For the two argument constructor,...

  • code the inverse function 5. Here is the outline of a Rational number class, i.e., a...

    code the inverse function 5. Here is the outline of a Rational number class, i.e., a class that contains fractional numbers represented by an integer numerator and denominator). class Rational ( << operator operator public: Rational (int num, int denom) operator inverse function moiionu o loino private: int num, denom For partial credit for parts a-c, you can code the *, Integer class and << operators for the a. Code the operator; the result of multiplying two rationals is a...

  • In mathematics, a rational number is any number that can be expressed as the quotient or...

    In mathematics, a rational number is any number that can be expressed as the quotient or fraction p/q of two integers, p and q, with the denominator q not equal to zero. Since q may be equal to 1, every integer is a rational number. Define a class that can represent for a rational number. Use the class in a C++ program that can perform all of the following operations with any two valid rational numbers entered at the keyboard...

  • Rational will be our parent class that I included to this post, Implement a sub-class MixedRational....

    Rational will be our parent class that I included to this post, Implement a sub-class MixedRational. This class should Implement not limited to: 1) a Constructor with a mathematically proper whole, numerator and denominator values as parameters. 2) You will override the: toString, add, subtract, multiply, and divide methods. You may need to implement some additional methods, enabling utilization of methods from rational. I have included a MixedRational class with the method headers that I used to meet these expectations....

  • C++ Create a Rational Number (fractions) class like the one in Exercise 9.6 of the textbook....

    C++ Create a Rational Number (fractions) class like the one in Exercise 9.6 of the textbook. Provide the following capabilities: Create a constructor that prevents a 0 denominator in a fraction, reduces or simplifies fractions (by dividing the numerator and the denominator by their greatest common divisor) that are not in reduced form, and avoids negative denominators. Overload the addition, subtraction, multiplication, and division operators for this class. Overload the relational and equality operators for this class. Provide a function...

  • Header file for the Rational class: #ifndef RATIONAL_H #define RATIONAL_H class Rational { public: Rational( int...

    Header file for the Rational class: #ifndef RATIONAL_H #define RATIONAL_H class Rational { public: Rational( int = 0, int = 1 ); // default constructor Rational addition( const Rational & ) const; // function addition Rational subtraction( const Rational & ) const; // function subtraction Rational multiplication( const Rational & ) const; // function multi. Rational division( const Rational & ) const; // function division void printRational () const; // print rational format void printRationalAsDouble() const; // print rational as...

  • (Rational class) Create a class called Rational for performing arithmetic with fractions. Write a program to...

    (Rational class) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integers variables to represent the private data of the class- the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should contain default values in case are no initializers are provided and should store the fraction in reduced form. For example, the fraction 3/6 would be...

  • Please use Java language. Thanks in advance. HOME WORK due 09. 18.2019 (Rational Numbers) Create a...

    Please use Java language. Thanks in advance. HOME WORK due 09. 18.2019 (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private instance variables of the class- the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it's declared. The constructor should store the fraction in reduced form. The fraction 2/4 is equivalent to 2...

  • (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write a program to...

    (Rational Numbers) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private instance variables of the class- the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it's declared. The constructor should store the fraction in reduced form. The fraction 2/4 is equivalent to h and would be stored in the object as 1 in the numerator...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT