Write a Java application
called ApproxPi.java.
The infinite sum
4 * ( 1/1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ... )
converges to the value of π. It is not practical to
compute an infinite sum on a computer, but you can
compute a partial sum using the first N terms of the
infinite sum.
Part 1: Write a program that asks the user for
the number of terms N to use when computing the partial
sum shown above. Your program should use Fraction
objects from type.lib to compute the partial sum
using N terms, and then output the sum as shown in the following
sample output (text in red is typed in by the user):
% java ApproxPi
How many terms do you want to sum? 1
The approximate value of pi is
4/1 = 4.0
The value of Math.PI is
3.141592653589793
%
% java ApproxPi
How many terms do you want to sum? 20
The approximate value of pi is
516197940314096/166966608033225 = 3.0916238066678385
The value of Math.PI is
3.141592653589793
%
% java ApproxPi
How many terms do you want to sum? 0
The approximate value of pi is
0/1 = 0.0
The value of Math.PI is
3.141592653589793
%
Get Part 1 working first.
Once you have, extend your program for Part 2.
You need to do both for full credit,
but you will receive partial marks
if you only succeed in finishing Part 1.
Part 2: Add some code that performs
friendly validation on the user input value for the
number of terms N. Your code should ensure that the
number of terms is always in the range 0 to 20.
Your program should produce the following output:
(text in red is typed in by the user)
% java ApproxPi
How many terms do you want to sum? -100
Number of terms must be from 0-20... try again: 100
Number of terms must be from 0-20... try again: -1
Number of terms must be from 0-20... try again: 21
Number of terms must be from 0-20... try again: 10
The approximate value of pi is
44257352/14549535 = 3.0418396189294024
The value of Math.PI is
3.141592653589793
|