Problem Set 1
Exer ises
whi h ompute the mean and varian e of the elements in data respe tively.
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()
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 =
In this se
tion, we will implement a number of simple numeri
al algorithms and data stru
tures
in Java. 1
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.
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
i=0
Sin
e the ea
h intermediate point appears twi
e in the sum, this
an be simplied 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);
the dieren
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.
Poly(int[ oef) { Constru tor from an array of oe ients [ where [n is the oe ient
of xn .
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
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 renements,
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
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).
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.
Zb
f (x)dx = F (b)
F (a)
where F (x) is the indenite integral of f (x). For a polynomial ai xi the indenite 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:
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
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 denition, instan
e vars and method denitions. 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:
These queues
an only hold Obje
t
lasses whi
h implement the Comparable interfa
e. (Note:
This interfa
e is dened in pa
kage java.util so you needn't redene 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 dieren
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: