

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


and program to calculate π
In mathematics, the rational numbers are defined as the set Q = { ab | a, b ∈ Integers ∧ b 6 = 0}. To develop a Java class to implement rational numbers, including the operations on them, we must first determine what invariants (rules), data members and member methods are necessary.
Invariants.
Data Members. A Rational class object will need to store a numerator and a denominator, both of type int. We shall need to guarantee they are always “in lowest (or reduced) terms” — in other words, that the numerator and denominator have no factors (other than 1 or −1) in common. Access to these data members should be restricted to the class itself — the client should not be able to manipulate the numerator or denominator directly.
Member Methods. When designing a class, it is necessary to consider what constructors, inspec- tors, mutators, and facilitators are required or might be useful.
Rules for rational arithmetic
Addition Multiplication a b +^
c d =^
ad+bc bd
a b ∗^
c d =^
ac bd Subtraction Division a b −^
c d =^
ad−bc bd
a b ÷^
c d =^
ad bc
MAT 2170: Rational Class 2
Also, the class should include the toString() method, which returns a string version of the fraction suitable for output. Another facilitator method should calculate the gcd(n, m) of two integers, for use in reducing the fraction.
There are many interesting ways to calculate π. For example^1 ,
π 2
or
π = 2
( 1 +
)
We would like a method, named piApproximation, which finds a rational approximation to π by using n terms of the series given above. For example, if n = 2, the result is 2(1 + 13 ) = 83. This method has one input parameter — the desired number of terms — and returns one value, as a rational number. We wish to use a modified version of the Rational class in our solution, as follows:
Lastly, we need a client program which asks the user for n (the desired number of terms), and outputs the sum of the first n terms of the series given above in two ways: as an exact rational value, and then again as a floating-point value. If you implement this program, you will need to keep n relatively small when you run it — even with the use of long-type numerators and denominators, you will get quite a few digits fairly quickly^2.
(^1) You can find this formula and many others at: http://mathworld.wolfram.com/PiFormulas.html. Calculating π is a mathematical problem of both historical and current interest. The references on the Wolfram site list dozens of articles about π, many written within the last twenty years. (^2) Exercise 10 (page 220) gives a hint how to solve this problem, using Java’s BigInteger class. That is a more ambitious problem and is not required for this lab assignment.