Anda di halaman 1dari 7

Obje

t-Oriented Programming in Java

Problem Set 1

Due: Jan 8, 2001

Exer ises

Exer ise 1: Hello World


Compile and run the Hello.java program. Modify the initial message, re ompilem, and re-run.
Add to Hello the re ursive and iterative fa torial methods from lass. Test these with alls from
main().

Exer ise 2: Arrays


Write and test stati methods
float Mean(float[ data)
float Varian e(float[ data)

whi h ompute the mean and varian e of the elements in data respe tively.

Exer ise 3: Re ursion and Iteration


Write a method that omputes b(x) re ursively using the re urren e
fib(0) = 1
fib(1) = 1
fib(x) = fib(x

1) + fib(x

2):

Now write a method that omputes b(x) iteratively. (Hint: Start from 0, and ompute the sum
forward, saving the last two values ea h iteration).
Test these by alling from main()

Exer ise 4: Command Arguments


Modify your main() routine from Exer ise 3 to take two arguments on the ommand line. The
rst is a string with values \I" or \R" whi h sele ts the Interative or Fa torial versions respe tively.
The se ond is an integer whi h is the arg to fib() (Remember to onvert this from String to int.
Hint: Use Integer.parseInt()).
Use the UNIX time ommand to time both versions on fib(10) and fib(40). Is there a moral
here?

Exer ise 5: Arrays: A Word Problem


If one lends D dollars at an (annual ompound) interest rate of r (ie r = 0.07 for 7% interest).
The investment, at the end of N years, will be worth D(1 + r)N dollars. Inverting this, to have a
nest-egg of D dollars in N years, one must invest D=(1 + r)N dollars today. This quantity is alled
the Net Present Value or Dis ounted Value of D dollars N years in the future. Some investments,
1

like sto ks and bonds, produ e an annual ash ow (Dt for year t). The net present value of su h
an asset is omputed by summing the Dis ounted ash ows for ea h year.
NP V =

X(D =(1 + r)t)


t

a) Write a stati method to ompute the NPV of an investment returning a onstant Dt = d


dollars for N years assuming an interest rate of r. (Assume the rst payment omes in year 0 and is
not dis ounted).
b) If you win $2,000,000 in the Lottery, rather than a he k for $2M, you will a tually re eive
$100,000 per year for the next 20 years. Call your method to al ulate the NPV of your prize
assuming r=0.06 (ie 6%). Compute the NPV for a 9% interest rate.
Problems

In this se tion, we will implement a number of simple numeri al algorithms and data stru tures
in Java. 1

Problem 1: Root Finding by Binary Sear h


One algorithm for omputing (approximately) the real roots of a ontinuous fun tion (i.e.; a
value R su h that f (R) = 0 ), is binary sear h. Suppose you know two values a and b su h that
f (a) and f (b) have opposite signs. By the intermediate value theorem, there is at least one root of
f between a and b. The root is said to be bra keted by a and b.
We an now trap the root to any a ura y by omputing f (x), where x = (a + b)=2 and omparing
to f (a) and f (b). If f (x) has the same sign as f (a), we know x < R < b, and if f (x) has the same
sign as f (b), we know a < R < x. We an iterate this pro edure to ompute the root to any desired
a ura y. Note that the error in our estimate is halved ea h iteration.
Write a driver lass Fun tionTest and implement the root bra keting algorithm as a stati
method:
publi stati double bra ketRoot(double a, double b, double maxerr);

Use Math.sin() as the fun tion to be evaluated. Call this method from main() to nd the root of
sin(x) between 3 and 4 to within 10 8.
Save your ode. You will submit it as part of Problem 4.

Problem 2: Numeri al Integration: Extended Trapezoidal Rule


Another useful numeri al algorithm omputes de nite integrals through use of the trapezoidal
approximation

Zb

f (x)dx  (b

a)

f (a) + f (b)
:
2

a
is not to imply that Java is the language of hoi e for numeri al algorithms, or algorithms in general.
Algorithms are generally about program speed and e ien y, Java and OOP are about programmer speed and
e ien y in onstru ting large systems. To quote Numeri al Re ipes in C, \The pra ti al s ientist is trying to
solve tomorrow's problems with today's hardware, omputer s ientists, it often seems, are doing the reverse."
1 This

This ( rude) approximation an be made more a urate by dividing the interval [a; b into N segments
of length h = (b a)=N , omputing the integral over ea h of the segments and summing the result.
2 The resulting approximation is

X1 h f (a + hi) + f (a + h(i + 1)) :

i=0

Sin e the ea h intermediate point appears twi e in the sum, this an be simpli ed to
h

X1

f (a) + f (b)
hf (a + hi):
+
2
i=1

Add a method to Fun tionTest that implements this algorithm on Math.sin() with the following signature:
publi stati double defIntegral(double a, double b, int N);

Use this method to ompute

R sin(x) and 2R sin(x). Choose N to be a power of two su h that


0

the di eren e between using N=2 and N is less than 10 8 (ie start at n = 1024 and double ea h
time). 3
Save your ode. You will submit it as part of Problem 4.

Problem 3: A Polynomial Class


Write a lass Poly representing polynomials with integer oe ients. Implement the following
methods:





Poly(int[ oef) { Constru tor from an array of oe ients [ where [n is the oe ient

of xn .

int degree() - returns the power of the highest non-zero term.


String toString() - returns a string representation of the polynomial (use \x" as the dummy
variable and format high-order to low-order powers).

Add addition and multipli ation in both stati and instan e forms:






Poly add(Poly a)
Poly mul(Poly a)
stati Poly add(Poly a, Poly b)
stati Poly mul(Poly a, Poly b)

Rather than implement substra tion, implement a s ale method, whi h multiplies all oe ient by
a onstant value. Subtra tion an them be implemented as p1.add(p2.s ale(-1));
2 Remember

the following property of integration:

f (x)dx =

f (x)dx +

f (x)dx

3 In order to nd an adequate value of N for a given problem, one must iterate over in reasing N and re- omputing
the integral. In this iteration, a lot of redundent work is performed. If N is doubled ea h time, it is possible to
improve this algorithm by only omputing the sum for points not omputed on the previous iteration ( omputed with
N=2 segments). This sum an be added to the result of the previous iteration to give the orre t approxiation for N
segments. For further re nements, onsult any numeri al algorithms text.

Poly s ale(int s)

Comment your lass with Javado ompatable omments and run Javado to produ e do umentation. Hint: Use the -d option to have the do umentation sent to a subdire tory of your working
dire tory.
Write a driver lass and test your implementation.
Download our PolyTest. lass driver into your working dire tory and run it.
Questions:

This is an immutable implementation of polynomials. Unary operators like s ale() return new
polynomials. What are the advantages and disadvantages of this hoi e?
What are the advantages and disadvantages of hoosing stati methods for binary operators vs.
instan e methods? (In this ase we do both).
Submit: The sour e to Poly.java and your test driver, the output of PolyTest, and your answers to
the questions.

Problem 4: Inheritan e
We will now use inheritan e to generalize the numeri al routines from the previous se tion.
Write a lass RFun whi h will represent the behavior of fun tions over the real numbers (or in
our ase, Java doubles). Sin e there is no su h thing as a generi fun tion, make RFun an abstra t
lass supporting the method

publi abstra t double evaluate(double x)

Generalize the bra ketRoot and defIntegral methods you wrote earlier, by repla ing the alls to
Math.sin() with alls to evaluate(), and add them as instan e methods to RFun . (Remember to
do ument RFun with Javado omments).




publi double bra ketRoot(double a, double b, double maxErr)


publi double defIntegral(double a, double b, int N)

Now that we have an abstra t fun tion lass, we need some real fun tions. Write sub lasses
of RFun , SinFun and CosFun , that override the evaluate() method to return Math.sin(x) and
Math. os(x) respe tively. Add JavaDo omments everywhere, as always.
Write a test driver to nd the root of os(x) between 1 and 3. Compute the integral of os(x)
from 0 to =2 and 0 to  .
Download and run the Fun Test. lass driver in your working dire tory and submit the results.
Submit:

The sour e to RFun .java, the output of Fun Test, and your answers to the questions.

Problem 5: Polynomials as Fun tions


Sin e polynomials an be onsidered as fun tions, modify Poly to be a sub lass of RFun (add an
evaluate() method). Modify your driver lass to ompute the positive root of x2 3 and x2 x 1.
Also ompute the integral of x2 4 from 0 to 2.
Re-run Javado on your fun tion lasses and browse the result.
4

Unlike arbitrary fun tions, polynomials an be integrated in losed form.

Zb

f (x)dx = F (b)

F (a)

where F (x) is the inde nite integral of f (x). For a polynomial ai xi the inde nite integral is
ai xi+1 . Use this prin iple to override the defIntegral method in Poly. Use your test program to
i+1
again ompute the integral of x2 4 from 0 to 2.
Download and run the Fun Test2. lass driver in your working dire tory and submit the results.
Submit:

The sour e to Poly.java and the output of Fun 2Test.

Problem 6: Interfa es
An alternate way to abstra t fun tions is as an interfa e. We an write an RFun Lib lass to be
a repository for the bra ketRoot and defIntegral methods, and use an interfa e Fun tion to hold
the evaluate method.
Write a Fun tion interfa e with one method, evaluate. Modify SinFun , CosFun and Poly to
implement Fun tion rather than extend RFun . Write the RFun Lib lass to ontain your numeri al
routines as stati methods. You will need to modify them to take an additional argument of type
Fun tion and use this as the fun tion to evaluate. Test this new implementation.
Download and run the Fun Test3. lass driver in your working dire tory.
Questions:

What are some reasons for hoosing the inheritan e-based approa h rather than interfa e-based
approa h and vi e-versa?
Submit:

questions.

The sour e to RFun Lib.java, Fun tion.java, the output of Fun Test3, and answers to

Problem 7: Class Design


Design a lass hierar hy ( lasses and/or interfa es) to support a program dealing with geographi
obje ts. Support the following lasses (at least):







Countries
States/Provin es
Cities
Boundary Segments
Rivers

Support the following operations, where appli able, plus any others that seem useful (arguments
have been omitted):





area()
apital()
getCities()
5







getCountry()
distan e() { between ities
boundaryLength() { total length of boundary
neighbors() { obje ts sharing boundaries
borderOf() { the ountries/states this separates

Write out the lass de nition, instan e vars and method de nitions. Don't bother to implement
the methods (but make sure you ould). Use interfa es and super lasses where appropriate. Supply
javado omments for all lasses, interfa es, and methods.
Note: This problem is deliberately openended. Don't pani !
Submit:

Your lass and method de nitions (in a single text le).

Problem 8: Priority Queue


Priority queues are ontainers that hold obje ts that an be ompared. That is have an order
relation equivalent to >. Obje t are inserted into a priority queue arbitrarily, but are removed in
sorted order. That is, the largest ( or smallest) element in the queue is removed and returned. The
basi PriorityQueue interfa e is
interfa e PriorityQueue{
/**
* Add an Obje t to the queue
*/
publi void insert(Comparable a);
/**
* Removes and returns the maximum obje t from the queue
*/
publi Comparable removeMax();
/**
* Returns true iff queue is empty
*
*/
publi boolean empty();
/**
* Returns the number of obje ts in the queue
*
*/
publi int length();
}

These queues an only hold Obje t lasses whi h implement the Comparable interfa e. (Note:
This interfa e is de ned in pa kage java.util so you needn't rede ne it.)
interfa e Comparable{
/*
* Return -1,0,or 1 depending on whether 'a' in less-than, equal to,
* or greater than the impli it arg (ie 'this') in the desired
* ordering.
*/
publi int ompareTo(Comparable a);
}

Write a lass PQueue that implements PriorityQueue. [Don't worry about e ien y. You an
use a linked list, doubly-linked list, array, or Ve tor as the underlying data stru ture. It is easiest
to sort the obje ts as they are inserted. Make sure the stru ture an grow to arbitrary size, yet
properly shrinks when items are removed.
The Java String and Integer lasses implement Comparable. Test your lass by inserting a
handful of Strings and removing them, verifying they ome out in the right order. Test that it still
work when you interleave inserts and removes.
Modify your Poly lass to implement Comparable. The ordering for polynomials: ompare
degrees rst, if degrees are equal, then ompare leading oe ients, if these are equal, ompare on
lower order terms.
Questions:

What happens if you insert some Strings then some Integers (remember: this is the lass wrapper
for int, not the int type). What happens if you try to removeMax()?
This reveals a problem with this type of abstra tion. Is there any good solution?
The java.utils pa kage has a lass TreeMap whi h implements similar fun tionality to PriorityQueue. It an use the Comparable interfa e to sort, but it also allows the spe i ation of a
Comparator obje t in the onstru tor. A Comparator is a lass with a binary ompare() fun tion.
The signi ant di eren e is that the Comparator is atta hed to the TreeMap rather than the elements themselves (as is the ase with the ompareTo method of Comparable). Does this solve the
problem en ountered above?
Submit:

PQueue.java and answers to questions.

Anda mungkin juga menyukai