SlideShare a Scribd company logo
CSC-1106 Homework 09 (Class and static methods) Due: Tuesday, November 22, 2016 Write a
class encapsulating the concept of a rational number, a rational number has the following
attributes: an integer representing the numerator of the number. number, and another integer
representing the denominator of the rational The ratio should always be stored in its simplest
form. For example, the rational number 40/12 should be stored as 103. The class has the
following constructors and methods: A default constructor to set the Rational number to 0/1 A
constructor that has parameters for the numerator and denominator, and converts the resulting
ratio to simplified form simplify 0-a private method to convert the Rational number to simplified
form getGCD (x, y) -a private static method to return the largest common factor of the two
positive integers x and y (their greatest common divisor). For example, the greatest common
divisor of 40 and 12 is 4. value 0-returns the Rational number as a double value o-returns the
Rational number as a string in the form a/b toString multiply (Rational -a public method to return
the Rational number after multiplied by Rational number r add (Rational r)-a public method to
return the Rational number after addition with Rational number r floor (Rational r) -a public
method to return the integer of the floor of the Rational number. max (Rational x, Rational )-a
public static method to return the larger Rational number among x and y.
Solution
public class Rational {
/**
* A public constant that defines the rational value of 0.
*/
public static final Rational ZERO = new Rational(0, 1);
/**
* A public constant that defines the rational value of 1.
*/
public static final Rational ONE = new Rational(1, 1);
/**
* A public constant that defines the rational value of 0.5.
*/
public static final Rational HALF = new Rational(1, 2);
/*
* The Lowest and the Highest levels of precision allowed.
*/
private static final double LWST_PREC = 1E-3;
private static final double HIST_PREC = 1E-16;
private static double precision = 1E-10;
private final long num;
private final long den;
private final double result;
/**
* Creates a new {@code Rational} with the given numerator and
* denominator. It has special cases for Positive Infinity
* ({@link java.lang.Double#POSITIVE_INFINITY Double.POSITIVE_INFINITY}),
* Negative Infinity ({@link java.lang.Double#NEGATIVE_INFINITY
* Double.NEGATIVE_INFINITY}) and Not A Number
* ({@link java.lang.Double#NaN Double.NaN}.
*
* @param numerator The numerator.
* @param denominator The denominator.
*/
public Rational(long numerator, long denominator) {
// for dealing with "infinities" and "NaN":
if (denominator == 0) {
den = 0;
if (numerator > 0) {
num = 1;
result = Double.POSITIVE_INFINITY;
} else if (numerator < 0) {
num = -1;
result = Double.NEGATIVE_INFINITY;
} else {
num = 0;
result = Double.NaN;
}
return;
}
if (denominator < 0) {
numerator = 0L - numerator;
denominator = 0L - denominator;
}
num = numerator;
den = denominator;
result = (double) numerator / denominator;
}
/**
* Creates a new {@code Rational} object that approximates the value of
* the decimal to the set level of {@link #getPrecision() precision}. It
* is also capable of approximating irrational values like
* {@link java.lang.Math#PI Math.PI}, {@link java.lang.Math#E Math.E} or
* the golden ratio, .
*
* @param decimal The value to approximate.
*/
public Rational(double decimal) {
// Exit clauses:
if (decimal == Double.NaN) {
num = 0;
den = 0;
result = Double.NaN;
return;
}
if (decimal == Double.POSITIVE_INFINITY) {
num = 1;
den = 0;
result = Double.POSITIVE_INFINITY;
return;
}
if (decimal == Double.NEGATIVE_INFINITY) {
num = -1;
den = 0;
result = Double.NEGATIVE_INFINITY;
return;
}
long nu, de;
long whole = 0; // fail-safe value
boolean negative = decimal < 0;
decimal = Math.abs(decimal);
boolean hasWhole = decimal >= 1;
if (hasWhole) { // keep fractional part.
whole = (long) decimal;
decimal -= whole;
}
if (decimal == 0) { // no fractional part present or 0 input
num = negative ? 0L - whole : whole;
den = 1;
result = negative ? 0D - whole : whole;
return;
}
// initially, the extreme points are 0 and 1.
// decimal always lies in the interval: (n1/d1, n2/d2)
long n1 = 0, d1 = 1;
long n2 = 1, d2 = 1;
double epsilon; // the error amount in the approximation.
while (true) {
long n = n1 + n2, d = d1 + d2;
double result = (double) n / d;
epsilon = Math.abs(result - decimal);
if (epsilon <= precision) { // goal reached
nu = n;
de = d;
break;
} else if (result < decimal) { // increase lower bound
n1 = n;
d1 = d;
} else { // increase upper bound
n2 = n;
d2 = d;
}
}
if (hasWhole) { // add the whole part to the fraction
nu += de * whole;
}
num = negative ? 0L - nu : nu;
den = de;
result = (double) num / den;
}
/**
* Returns the set level of precision. The default level of
* precision is {@code 1.0E-10}, unless changed.
*
* @return The level of precision.
*/
public static double getPrecision() {
return precision;
}
/**
* Changes the set level of precision. However, the maximum and minimum
* levels of precision are defined and the value of precision
* snaps to these values if the parameter is more or
* less than them, respectively.
*
* @param precision The level of precision to set.
*/
public static void setPrecision(double precision) {
if (precision < 0) precision = 0D - precision;
if (precision < HIST_PREC) precision = HIST_PREC;
else if (precision > LWST_PREC) precision = LWST_PREC;
Rational.precision = precision;
}
// public long getNum() {
// return num;
// }
// public long getDen() {
// return den;
// }
/**
* Returns the Highest Common Factor of two integers. It employs the
* Euclidean division method.
*
* @param a One of the two numbers.
* @param b The other number.
* @return The H.C.F of {@code a} and {@code b}.
*/
private static long hcf(long a, long b) {
if (a == 0 || b == 0) {
return 0; // ???
}
// turn all the negative arguments to positive.
if (a < 0) a = 0L - a;
if (b < 0) b = 0L - b;
if (a < b) {
long t = a;
a = b;
b = t;
}
long r;
do {
r = a % b;
a = b;
b = r;
} while (r > 0);
return a;
}
// Demo
public static void main(String[] args) {
Rational PI = new Rational(Math.PI);
System.out.println("Pi = " + PI);
}
/**
* This method returns the {@code Rational} object that is the reduced
* form of {@code this Rational}. (More specifically,
* the numerator and denominator have no common factor.)
*
* @return The reduced form of {@code this Rational}.
*/
public Rational reduce() {
long hcf = hcf(num, den);
if (hcf == 0) { // infinities and NaN
return this;
} else {
long n = num / hcf;
long d = den / hcf;
return new Rational(n, d);
}
}
/**
* Returns the sum of {@code rational} with {@code this}.
*
* @param rational The {@code Rational} to add.
* @return Their sum.
*/
public Rational add(Rational rational) {
if (this.result == Double.NaN) {
return this;
} else //noinspection ConstantConditions
if (rational.result == Double.NaN) {
return rational;
}
Rational o = reduce();
long n1 = o.num, d1 = o.den;
o = rational.reduce();
long n2 = o.num, d2 = o.den;
return new Rational(n1 * d2 + n2 * d1, d1 * d2).reduce();
}
/**
* Returns the difference of {@code rational} with {@code this}.
*
* @param rational The {@code Rational} to subtract.
* @return Their difference.
*/
public Rational subtract(Rational rational) {
return add(new Rational(0L - rational.num, rational.den));
}
/**
* Returns the product of {@code rational} and {@code this}.
*
* @param rational The {@code Rational} to multiply with.
* @return Their product.
*/
public Rational multiply(Rational rational) {
return new Rational(
this.num * rational.num,
this.den * rational.den)
.reduce();
}
/**
* Divides {@code this} with {@code rational}.
*
* @param rational The divisor.
* @return The required quotient.
*/
public Rational divide(Rational rational) {
return multiply(rational.reciprocate());
}
/**
* Returns the reciprocal of {@code this}.
*
* @return the reciprocal of {@code this}.
*/
public Rational reciprocate() {
return new Rational(den, num);
}
/**
* Returns the {@code double} representation of tis {@code Rational}.
*
* @return the {@code double} representation of tis {@code Rational}.
*/
public double toDouble() {
return result;
}
/**
* Returns the {@code String} representation of tis {@code Rational}.
*
* @return the {@code String} representation of tis {@code Rational}.
*/
@Override
public String toString() {
return Long.toString(num).concat("/").concat(Long.toString(den));
}
/**
* Compares {@code this} object with another with respect to class and
* then the values of the numerator and denominator.
*
* @param another The {@code Object} to compare with.
* @return {@code true} if the objects are equal, {@code false} otherwise.
*/
@Override
public boolean equals(Object another) {
if (another instanceof Rational) {
Rational oldF = reduce();
Rational newF = ((Rational) another).reduce();
return (oldF.num == newF.num) &&
(oldF.den == newF.den);
}
return false;
}
/**
* Returns {@code this} to the power {@code p}.
*
* @param p The power to be raised to.
* @return {@code this} to the power {@code p}.
*/
public Rational pow(int p) {
Rational result = ONE;
Rational n = new Rational(num, den);
boolean neg = p < 0;
if (neg) p = 0 - p;
while (p > 0) {
if ((p & 1) == 1) {
result = result.multiply(n);
p--;
}
n = n.multiply(n);
p >>>= 1;
}
return neg ? result.reciprocate() : result;
}
/**
* Returns {@code this} to the fractional power {@code p}.
*
* @param p The power to be raised to.
* @return {@code this} to the power {@code p}.
*/
public Rational pow(Rational p) {
return new Rational(Math.pow(this.result, p.result));
}
}
RationalTest.java
import junit.framework.TestCase;
public class RationalTest extends TestCase {
public void testAdd() {
Rational r1, r2;
r1 = new Rational(10, 20);
r2 = new Rational(20, 30);
assertEquals(new Rational(7, 6), r1.add(r2));
}
public void testSubtract() {
Rational r1, r2;
r1 = new Rational(20, 30);
r2 = new Rational(10, 20);
assertEquals(new Rational(1, 6), r1.subtract(r2));
}
public void testMultiply() {
Rational r1, r2;
r1 = new Rational(0.5);
r2 = new Rational(2);
assertEquals(Rational.ONE, r1.multiply(r2));
}
public void testDivide() {
Rational r1, r2;
r1 = new Rational(0.5);
r2 = new Rational(0.0625);
assertEquals(new Rational(8), r1.divide(r2));
}
public void testPow() {
assertEquals(Rational.ONE, new Rational(2).pow(Rational.ZERO));
assertEquals(new Rational(1, 64), new Rational(1, 4).pow(3));
}
}

More Related Content

Similar to CSC-1106 Homework 09 (Class and static methods) Due Tuesday, Novembe.pdf

1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
hara69
 
So here is the code from the previous assignment that we need to ext.pdf
So here is the code from the previous assignment that we need to ext.pdfSo here is the code from the previous assignment that we need to ext.pdf
So here is the code from the previous assignment that we need to ext.pdf
leolight2
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Codemotion
 
For this micro assignment, you must implement two Linked List functi.docx
For this micro assignment, you must implement two Linked List functi.docxFor this micro assignment, you must implement two Linked List functi.docx
For this micro assignment, you must implement two Linked List functi.docx
mckellarhastings
 
I have to write a polynomial class linked list program and i do not .pdf
I have to write a polynomial class linked list program and i do not .pdfI have to write a polynomial class linked list program and i do not .pdf
I have to write a polynomial class linked list program and i do not .pdf
jibinsh
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
40+ examples of user defined methods in java with explanation
40+ examples of user defined methods in java with explanation40+ examples of user defined methods in java with explanation
40+ examples of user defined methods in java with explanation
Harish Gyanani
 
C++ Function
C++ FunctionC++ Function
C++ FunctionHajar
 
Java code to find the closest pair using divide and conquer algorith.pdf
Java code to find the closest pair using divide and conquer algorith.pdfJava code to find the closest pair using divide and conquer algorith.pdf
Java code to find the closest pair using divide and conquer algorith.pdf
fashioncollection2
 
Hive Functions Cheat Sheet
Hive Functions Cheat SheetHive Functions Cheat Sheet
Hive Functions Cheat Sheet
Hortonworks
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
jyothimuppasani1
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
priestmanmable
 
7 functions
7  functions7  functions
7 functions
MomenMostafa
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
amrit47
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3rohassanie
 
Main issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdfMain issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdf
aonesalem
 
In this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfIn this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdf
contact41
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
JoeyDelaCruz22
 

Similar to CSC-1106 Homework 09 (Class and static methods) Due Tuesday, Novembe.pdf (20)

1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
 
So here is the code from the previous assignment that we need to ext.pdf
So here is the code from the previous assignment that we need to ext.pdfSo here is the code from the previous assignment that we need to ext.pdf
So here is the code from the previous assignment that we need to ext.pdf
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Functional object
Functional objectFunctional object
Functional object
 
For this micro assignment, you must implement two Linked List functi.docx
For this micro assignment, you must implement two Linked List functi.docxFor this micro assignment, you must implement two Linked List functi.docx
For this micro assignment, you must implement two Linked List functi.docx
 
I have to write a polynomial class linked list program and i do not .pdf
I have to write a polynomial class linked list program and i do not .pdfI have to write a polynomial class linked list program and i do not .pdf
I have to write a polynomial class linked list program and i do not .pdf
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
40+ examples of user defined methods in java with explanation
40+ examples of user defined methods in java with explanation40+ examples of user defined methods in java with explanation
40+ examples of user defined methods in java with explanation
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Java code to find the closest pair using divide and conquer algorith.pdf
Java code to find the closest pair using divide and conquer algorith.pdfJava code to find the closest pair using divide and conquer algorith.pdf
Java code to find the closest pair using divide and conquer algorith.pdf
 
Hive Functions Cheat Sheet
Hive Functions Cheat SheetHive Functions Cheat Sheet
Hive Functions Cheat Sheet
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
 
7 functions
7  functions7  functions
7 functions
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
 
FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3FP 201 Unit 2 - Part 3
FP 201 Unit 2 - Part 3
 
Main issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdfMain issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdf
 
In this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfIn this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdf
 
C++ Pointers with Examples.docx
C++ Pointers with Examples.docxC++ Pointers with Examples.docx
C++ Pointers with Examples.docx
 

More from marketing413921

Complete the implementation of the Weighted Graph that we began in t.pdf
Complete the implementation of the Weighted Graph that we began in t.pdfComplete the implementation of the Weighted Graph that we began in t.pdf
Complete the implementation of the Weighted Graph that we began in t.pdf
marketing413921
 
Can someone help me please I need help writing this code using Java.pdf
Can someone help me please I need help writing this code using Java.pdfCan someone help me please I need help writing this code using Java.pdf
Can someone help me please I need help writing this code using Java.pdf
marketing413921
 
C++ in XcodePass the values by reference to complete the programmi.pdf
C++ in XcodePass the values by reference to complete the programmi.pdfC++ in XcodePass the values by reference to complete the programmi.pdf
C++ in XcodePass the values by reference to complete the programmi.pdf
marketing413921
 
Assume an infix expression can only contain five operators, + .pdf
Assume an infix expression can only contain five operators,    + .pdfAssume an infix expression can only contain five operators,    + .pdf
Assume an infix expression can only contain five operators, + .pdf
marketing413921
 
appropriate nursing interventionsmanagement -COPD -Crackles, wheezi.pdf
appropriate nursing interventionsmanagement -COPD -Crackles, wheezi.pdfappropriate nursing interventionsmanagement -COPD -Crackles, wheezi.pdf
appropriate nursing interventionsmanagement -COPD -Crackles, wheezi.pdf
marketing413921
 
Arrange the following event in chronological order. The Roman Republi.pdf
Arrange the following event in chronological order. The Roman Republi.pdfArrange the following event in chronological order. The Roman Republi.pdf
Arrange the following event in chronological order. The Roman Republi.pdf
marketing413921
 
Why do we need internal control in an organization What is its purp.pdf
Why do we need internal control in an organization What is its purp.pdfWhy do we need internal control in an organization What is its purp.pdf
Why do we need internal control in an organization What is its purp.pdf
marketing413921
 
Why Diamond and semiconductor material like Silicon are used in elect.pdf
Why Diamond and semiconductor material like Silicon are used in elect.pdfWhy Diamond and semiconductor material like Silicon are used in elect.pdf
Why Diamond and semiconductor material like Silicon are used in elect.pdf
marketing413921
 
Which of the following was NOT a goal of Titchener’s psychologyA..pdf
Which of the following was NOT a goal of Titchener’s psychologyA..pdfWhich of the following was NOT a goal of Titchener’s psychologyA..pdf
Which of the following was NOT a goal of Titchener’s psychologyA..pdf
marketing413921
 
You discover a new kind of fungus with large, square-shaped spores. .pdf
You discover a new kind of fungus with large, square-shaped spores. .pdfYou discover a new kind of fungus with large, square-shaped spores. .pdf
You discover a new kind of fungus with large, square-shaped spores. .pdf
marketing413921
 
Write 1-2 pages of the definitions of the followings (Use APA forma.pdf
Write 1-2 pages of the definitions of the followings (Use APA forma.pdfWrite 1-2 pages of the definitions of the followings (Use APA forma.pdf
Write 1-2 pages of the definitions of the followings (Use APA forma.pdf
marketing413921
 
Which cell type does not move materials Which of the following cell .pdf
Which cell type does not move materials  Which of the following cell .pdfWhich cell type does not move materials  Which of the following cell .pdf
Which cell type does not move materials Which of the following cell .pdf
marketing413921
 
What is the practical relevanceirrelevance of different digital med.pdf
What is the practical relevanceirrelevance of different digital med.pdfWhat is the practical relevanceirrelevance of different digital med.pdf
What is the practical relevanceirrelevance of different digital med.pdf
marketing413921
 
using MATLABplease write down the code to compute these functions.pdf
using MATLABplease write down the code to compute these functions.pdfusing MATLABplease write down the code to compute these functions.pdf
using MATLABplease write down the code to compute these functions.pdf
marketing413921
 
What are the main duties of the Canadian Engineering Accreditation B.pdf
What are the main duties of the Canadian Engineering Accreditation B.pdfWhat are the main duties of the Canadian Engineering Accreditation B.pdf
What are the main duties of the Canadian Engineering Accreditation B.pdf
marketing413921
 
A supererogatory action is one in which a person must engage. T or F.pdf
A supererogatory action is one in which a person must engage. T or F.pdfA supererogatory action is one in which a person must engage. T or F.pdf
A supererogatory action is one in which a person must engage. T or F.pdf
marketing413921
 
The purpose of specialized lacunae are to provide structure to th.pdf
The purpose of specialized lacunae are to  provide structure to th.pdfThe purpose of specialized lacunae are to  provide structure to th.pdf
The purpose of specialized lacunae are to provide structure to th.pdf
marketing413921
 
The following code is an implementation of the producer consumer pro.pdf
The following code is an implementation of the producer consumer pro.pdfThe following code is an implementation of the producer consumer pro.pdf
The following code is an implementation of the producer consumer pro.pdf
marketing413921
 
Prerequisites — Classes or Knowledge Required for this Course.pdf
Prerequisites — Classes or Knowledge Required for this Course.pdfPrerequisites — Classes or Knowledge Required for this Course.pdf
Prerequisites — Classes or Knowledge Required for this Course.pdf
marketing413921
 
Please dont answer if you cannot complete all the requirements. Th.pdf
Please dont answer if you cannot complete all the requirements. Th.pdfPlease dont answer if you cannot complete all the requirements. Th.pdf
Please dont answer if you cannot complete all the requirements. Th.pdf
marketing413921
 

More from marketing413921 (20)

Complete the implementation of the Weighted Graph that we began in t.pdf
Complete the implementation of the Weighted Graph that we began in t.pdfComplete the implementation of the Weighted Graph that we began in t.pdf
Complete the implementation of the Weighted Graph that we began in t.pdf
 
Can someone help me please I need help writing this code using Java.pdf
Can someone help me please I need help writing this code using Java.pdfCan someone help me please I need help writing this code using Java.pdf
Can someone help me please I need help writing this code using Java.pdf
 
C++ in XcodePass the values by reference to complete the programmi.pdf
C++ in XcodePass the values by reference to complete the programmi.pdfC++ in XcodePass the values by reference to complete the programmi.pdf
C++ in XcodePass the values by reference to complete the programmi.pdf
 
Assume an infix expression can only contain five operators, + .pdf
Assume an infix expression can only contain five operators,    + .pdfAssume an infix expression can only contain five operators,    + .pdf
Assume an infix expression can only contain five operators, + .pdf
 
appropriate nursing interventionsmanagement -COPD -Crackles, wheezi.pdf
appropriate nursing interventionsmanagement -COPD -Crackles, wheezi.pdfappropriate nursing interventionsmanagement -COPD -Crackles, wheezi.pdf
appropriate nursing interventionsmanagement -COPD -Crackles, wheezi.pdf
 
Arrange the following event in chronological order. The Roman Republi.pdf
Arrange the following event in chronological order. The Roman Republi.pdfArrange the following event in chronological order. The Roman Republi.pdf
Arrange the following event in chronological order. The Roman Republi.pdf
 
Why do we need internal control in an organization What is its purp.pdf
Why do we need internal control in an organization What is its purp.pdfWhy do we need internal control in an organization What is its purp.pdf
Why do we need internal control in an organization What is its purp.pdf
 
Why Diamond and semiconductor material like Silicon are used in elect.pdf
Why Diamond and semiconductor material like Silicon are used in elect.pdfWhy Diamond and semiconductor material like Silicon are used in elect.pdf
Why Diamond and semiconductor material like Silicon are used in elect.pdf
 
Which of the following was NOT a goal of Titchener’s psychologyA..pdf
Which of the following was NOT a goal of Titchener’s psychologyA..pdfWhich of the following was NOT a goal of Titchener’s psychologyA..pdf
Which of the following was NOT a goal of Titchener’s psychologyA..pdf
 
You discover a new kind of fungus with large, square-shaped spores. .pdf
You discover a new kind of fungus with large, square-shaped spores. .pdfYou discover a new kind of fungus with large, square-shaped spores. .pdf
You discover a new kind of fungus with large, square-shaped spores. .pdf
 
Write 1-2 pages of the definitions of the followings (Use APA forma.pdf
Write 1-2 pages of the definitions of the followings (Use APA forma.pdfWrite 1-2 pages of the definitions of the followings (Use APA forma.pdf
Write 1-2 pages of the definitions of the followings (Use APA forma.pdf
 
Which cell type does not move materials Which of the following cell .pdf
Which cell type does not move materials  Which of the following cell .pdfWhich cell type does not move materials  Which of the following cell .pdf
Which cell type does not move materials Which of the following cell .pdf
 
What is the practical relevanceirrelevance of different digital med.pdf
What is the practical relevanceirrelevance of different digital med.pdfWhat is the practical relevanceirrelevance of different digital med.pdf
What is the practical relevanceirrelevance of different digital med.pdf
 
using MATLABplease write down the code to compute these functions.pdf
using MATLABplease write down the code to compute these functions.pdfusing MATLABplease write down the code to compute these functions.pdf
using MATLABplease write down the code to compute these functions.pdf
 
What are the main duties of the Canadian Engineering Accreditation B.pdf
What are the main duties of the Canadian Engineering Accreditation B.pdfWhat are the main duties of the Canadian Engineering Accreditation B.pdf
What are the main duties of the Canadian Engineering Accreditation B.pdf
 
A supererogatory action is one in which a person must engage. T or F.pdf
A supererogatory action is one in which a person must engage. T or F.pdfA supererogatory action is one in which a person must engage. T or F.pdf
A supererogatory action is one in which a person must engage. T or F.pdf
 
The purpose of specialized lacunae are to provide structure to th.pdf
The purpose of specialized lacunae are to  provide structure to th.pdfThe purpose of specialized lacunae are to  provide structure to th.pdf
The purpose of specialized lacunae are to provide structure to th.pdf
 
The following code is an implementation of the producer consumer pro.pdf
The following code is an implementation of the producer consumer pro.pdfThe following code is an implementation of the producer consumer pro.pdf
The following code is an implementation of the producer consumer pro.pdf
 
Prerequisites — Classes or Knowledge Required for this Course.pdf
Prerequisites — Classes or Knowledge Required for this Course.pdfPrerequisites — Classes or Knowledge Required for this Course.pdf
Prerequisites — Classes or Knowledge Required for this Course.pdf
 
Please dont answer if you cannot complete all the requirements. Th.pdf
Please dont answer if you cannot complete all the requirements. Th.pdfPlease dont answer if you cannot complete all the requirements. Th.pdf
Please dont answer if you cannot complete all the requirements. Th.pdf
 

Recently uploaded

How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 

Recently uploaded (20)

How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 

CSC-1106 Homework 09 (Class and static methods) Due Tuesday, Novembe.pdf

  • 1. CSC-1106 Homework 09 (Class and static methods) Due: Tuesday, November 22, 2016 Write a class encapsulating the concept of a rational number, a rational number has the following attributes: an integer representing the numerator of the number. number, and another integer representing the denominator of the rational The ratio should always be stored in its simplest form. For example, the rational number 40/12 should be stored as 103. The class has the following constructors and methods: A default constructor to set the Rational number to 0/1 A constructor that has parameters for the numerator and denominator, and converts the resulting ratio to simplified form simplify 0-a private method to convert the Rational number to simplified form getGCD (x, y) -a private static method to return the largest common factor of the two positive integers x and y (their greatest common divisor). For example, the greatest common divisor of 40 and 12 is 4. value 0-returns the Rational number as a double value o-returns the Rational number as a string in the form a/b toString multiply (Rational -a public method to return the Rational number after multiplied by Rational number r add (Rational r)-a public method to return the Rational number after addition with Rational number r floor (Rational r) -a public method to return the integer of the floor of the Rational number. max (Rational x, Rational )-a public static method to return the larger Rational number among x and y. Solution public class Rational { /** * A public constant that defines the rational value of 0. */ public static final Rational ZERO = new Rational(0, 1); /** * A public constant that defines the rational value of 1. */ public static final Rational ONE = new Rational(1, 1); /** * A public constant that defines the rational value of 0.5. */ public static final Rational HALF = new Rational(1, 2); /* * The Lowest and the Highest levels of precision allowed. */ private static final double LWST_PREC = 1E-3;
  • 2. private static final double HIST_PREC = 1E-16; private static double precision = 1E-10; private final long num; private final long den; private final double result; /** * Creates a new {@code Rational} with the given numerator and * denominator. It has special cases for Positive Infinity * ({@link java.lang.Double#POSITIVE_INFINITY Double.POSITIVE_INFINITY}), * Negative Infinity ({@link java.lang.Double#NEGATIVE_INFINITY * Double.NEGATIVE_INFINITY}) and Not A Number * ({@link java.lang.Double#NaN Double.NaN}. * * @param numerator The numerator. * @param denominator The denominator. */ public Rational(long numerator, long denominator) { // for dealing with "infinities" and "NaN": if (denominator == 0) { den = 0; if (numerator > 0) { num = 1; result = Double.POSITIVE_INFINITY; } else if (numerator < 0) { num = -1; result = Double.NEGATIVE_INFINITY; } else { num = 0; result = Double.NaN; } return; } if (denominator < 0) { numerator = 0L - numerator; denominator = 0L - denominator; }
  • 3. num = numerator; den = denominator; result = (double) numerator / denominator; } /** * Creates a new {@code Rational} object that approximates the value of * the decimal to the set level of {@link #getPrecision() precision}. It * is also capable of approximating irrational values like * {@link java.lang.Math#PI Math.PI}, {@link java.lang.Math#E Math.E} or * the golden ratio, . * * @param decimal The value to approximate. */ public Rational(double decimal) { // Exit clauses: if (decimal == Double.NaN) { num = 0; den = 0; result = Double.NaN; return; } if (decimal == Double.POSITIVE_INFINITY) { num = 1; den = 0; result = Double.POSITIVE_INFINITY; return; } if (decimal == Double.NEGATIVE_INFINITY) { num = -1; den = 0; result = Double.NEGATIVE_INFINITY; return; } long nu, de; long whole = 0; // fail-safe value boolean negative = decimal < 0;
  • 4. decimal = Math.abs(decimal); boolean hasWhole = decimal >= 1; if (hasWhole) { // keep fractional part. whole = (long) decimal; decimal -= whole; } if (decimal == 0) { // no fractional part present or 0 input num = negative ? 0L - whole : whole; den = 1; result = negative ? 0D - whole : whole; return; } // initially, the extreme points are 0 and 1. // decimal always lies in the interval: (n1/d1, n2/d2) long n1 = 0, d1 = 1; long n2 = 1, d2 = 1; double epsilon; // the error amount in the approximation. while (true) { long n = n1 + n2, d = d1 + d2; double result = (double) n / d; epsilon = Math.abs(result - decimal); if (epsilon <= precision) { // goal reached nu = n; de = d; break; } else if (result < decimal) { // increase lower bound n1 = n; d1 = d; } else { // increase upper bound n2 = n; d2 = d; } } if (hasWhole) { // add the whole part to the fraction nu += de * whole; }
  • 5. num = negative ? 0L - nu : nu; den = de; result = (double) num / den; } /** * Returns the set level of precision. The default level of * precision is {@code 1.0E-10}, unless changed. * * @return The level of precision. */ public static double getPrecision() { return precision; } /** * Changes the set level of precision. However, the maximum and minimum * levels of precision are defined and the value of precision * snaps to these values if the parameter is more or * less than them, respectively. * * @param precision The level of precision to set. */ public static void setPrecision(double precision) { if (precision < 0) precision = 0D - precision; if (precision < HIST_PREC) precision = HIST_PREC; else if (precision > LWST_PREC) precision = LWST_PREC; Rational.precision = precision; } // public long getNum() { // return num; // } // public long getDen() { // return den; // } /** * Returns the Highest Common Factor of two integers. It employs the * Euclidean division method.
  • 6. * * @param a One of the two numbers. * @param b The other number. * @return The H.C.F of {@code a} and {@code b}. */ private static long hcf(long a, long b) { if (a == 0 || b == 0) { return 0; // ??? } // turn all the negative arguments to positive. if (a < 0) a = 0L - a; if (b < 0) b = 0L - b; if (a < b) { long t = a; a = b; b = t; } long r; do { r = a % b; a = b; b = r; } while (r > 0); return a; } // Demo public static void main(String[] args) { Rational PI = new Rational(Math.PI); System.out.println("Pi = " + PI); } /** * This method returns the {@code Rational} object that is the reduced * form of {@code this Rational}. (More specifically, * the numerator and denominator have no common factor.) * * @return The reduced form of {@code this Rational}.
  • 7. */ public Rational reduce() { long hcf = hcf(num, den); if (hcf == 0) { // infinities and NaN return this; } else { long n = num / hcf; long d = den / hcf; return new Rational(n, d); } } /** * Returns the sum of {@code rational} with {@code this}. * * @param rational The {@code Rational} to add. * @return Their sum. */ public Rational add(Rational rational) { if (this.result == Double.NaN) { return this; } else //noinspection ConstantConditions if (rational.result == Double.NaN) { return rational; } Rational o = reduce(); long n1 = o.num, d1 = o.den; o = rational.reduce(); long n2 = o.num, d2 = o.den; return new Rational(n1 * d2 + n2 * d1, d1 * d2).reduce(); } /** * Returns the difference of {@code rational} with {@code this}. * * @param rational The {@code Rational} to subtract. * @return Their difference. */
  • 8. public Rational subtract(Rational rational) { return add(new Rational(0L - rational.num, rational.den)); } /** * Returns the product of {@code rational} and {@code this}. * * @param rational The {@code Rational} to multiply with. * @return Their product. */ public Rational multiply(Rational rational) { return new Rational( this.num * rational.num, this.den * rational.den) .reduce(); } /** * Divides {@code this} with {@code rational}. * * @param rational The divisor. * @return The required quotient. */ public Rational divide(Rational rational) { return multiply(rational.reciprocate()); } /** * Returns the reciprocal of {@code this}. * * @return the reciprocal of {@code this}. */ public Rational reciprocate() { return new Rational(den, num); } /** * Returns the {@code double} representation of tis {@code Rational}. * * @return the {@code double} representation of tis {@code Rational}.
  • 9. */ public double toDouble() { return result; } /** * Returns the {@code String} representation of tis {@code Rational}. * * @return the {@code String} representation of tis {@code Rational}. */ @Override public String toString() { return Long.toString(num).concat("/").concat(Long.toString(den)); } /** * Compares {@code this} object with another with respect to class and * then the values of the numerator and denominator. * * @param another The {@code Object} to compare with. * @return {@code true} if the objects are equal, {@code false} otherwise. */ @Override public boolean equals(Object another) { if (another instanceof Rational) { Rational oldF = reduce(); Rational newF = ((Rational) another).reduce(); return (oldF.num == newF.num) && (oldF.den == newF.den); } return false; } /** * Returns {@code this} to the power {@code p}. * * @param p The power to be raised to. * @return {@code this} to the power {@code p}. */
  • 10. public Rational pow(int p) { Rational result = ONE; Rational n = new Rational(num, den); boolean neg = p < 0; if (neg) p = 0 - p; while (p > 0) { if ((p & 1) == 1) { result = result.multiply(n); p--; } n = n.multiply(n); p >>>= 1; } return neg ? result.reciprocate() : result; } /** * Returns {@code this} to the fractional power {@code p}. * * @param p The power to be raised to. * @return {@code this} to the power {@code p}. */ public Rational pow(Rational p) { return new Rational(Math.pow(this.result, p.result)); } } RationalTest.java import junit.framework.TestCase; public class RationalTest extends TestCase { public void testAdd() { Rational r1, r2; r1 = new Rational(10, 20); r2 = new Rational(20, 30); assertEquals(new Rational(7, 6), r1.add(r2)); } public void testSubtract() { Rational r1, r2;
  • 11. r1 = new Rational(20, 30); r2 = new Rational(10, 20); assertEquals(new Rational(1, 6), r1.subtract(r2)); } public void testMultiply() { Rational r1, r2; r1 = new Rational(0.5); r2 = new Rational(2); assertEquals(Rational.ONE, r1.multiply(r2)); } public void testDivide() { Rational r1, r2; r1 = new Rational(0.5); r2 = new Rational(0.0625); assertEquals(new Rational(8), r1.divide(r2)); } public void testPow() { assertEquals(Rational.ONE, new Rational(2).pow(Rational.ZERO)); assertEquals(new Rational(1, 64), new Rational(1, 4).pow(3)); } }