Free University of Bolzano/Bozen
Faculty of Computer Science - Bachelor in Applied Computer Science
Bachelor in Production Engineering
Introduction to Programming - A.A. 2005/2006

Exercise
Function sampling


Part 1

A sample is a function y = f(x) defined only for given values of x (called sample points). The x values are often equally spaced.

Consider the sample with the following properties:

The i-th sample value (for i = 0, .., n-1) is

yi = f(xi),

where xi is the i-th sample point xi = x0 + i · dx.


Design and implement a class Sample that models a sample as explained above. The function to be sampled is given as y = 2 · x + 3, whereas the initial sample point, the interval and the number of samples are variables with different values for each instance of class Sample.

Fit the class with the following public methods:

Solution: Sample.java


Part 2

Implement a class SampleTools. It should include a public, static method integrate, that accepts a Sample object as parameter and computes an approximation of the integral of the sampled function in the interval [x0, xn-1] by adding all sample values for i = 0, ..., n-1 multiplied by the sample interval dx according to the summation formula:


This method just computes the rectangle's area as shown in the figure, which is an approximation to the integral:

Solution: SampleTools.java


Part 3

Implement a client class Client with a main method that asks the user to enter the initial sample point, the sample interval and the number of samples. The programm should create a instance of Sample. It should then call toString on the instance to print the samples.
Finally, it should compute and print the integral approximation of the sampled function.

Solution: Client.java


Part 4 (Note: the solution of this part requires the use of inheritance

Implement two classes SquareRootSample and SineSample, each derived from class Sample. The new classes should redefine the method sampleValue in order to return the values of y = sqrt(x) and y = sin(x) respectively.

Implement a client class Client2 with a main method that asks the user to enter the initial sample point, the sample interval and the number of samples. The programm should create an instance of SquareRootSample and one of SineSample. It should then call toString on each instance to print the samples.
Finally, it should compute and print the integral approximation for each of the two sampled functions.

Solutions: SquareRootSample.java, SineSample.java, Client2.java