Java Reference
In-Depth Information
public class
Rational {
static final double
PRECISION
#
10;
static final double
EPSILON
#
Math.pow(10,-PRECISION);
double
numerator
#
0.0;
double
denominator
#
1.0;
public
Rational(
double
num,
double
den) {
numerator
#
num;
denominator
#
den;
simplify();
}
public
Rational(
double
number) {
numerator
#
number;
denominator
#
1.0;
canonical();
simplify();
}
The constructors make use of two methods:
canonical()
and
simplify()
. The
former ensures that numerator and denominator are both integers, with an
approximation of ten decimal figures. The latter simplifies the fraction by
dividing both numerator and denominator by their common divisors.
void
canonical() {
double
num
#
Math.abs(numerator);
double
decimal
#
num - Math.floor(num);
int
num_digits
#
0;
while
(decimal > EPSILON && num_digits < PRECISION) {
num
#
num * 10;
decimal
#
num - Math.floor(num);
num_digits
!!
;
}
numerator
#
numerator * Math.pow(10.0, num_digits);
denominator
#
denominator * Math.pow(10.0, num_digits);
}
public
void simplify() {
double
divisor
#
Math.min(Math.abs(numerator),
denominator);
for
(; divisor > 1.0; divisor -
#
1.0) {
double
rn
#
Math.abs(Math.IEEEremainder(
Math.abs(numerator), divisor));
double
rd
#
Math.abs(Math.IEEEremainder
(denominator, divisor));
if
(rn < EPSILON && rd < EPSILON) {
numerator /
#
divisor;
denominator /
#
divisor;
divisor
#
Math.min(Math.abs(numerator),
denominator);
}
}
}