Home
|
Course Outline
|
Lectures
|
Homework
|
Files
The extended trapezoidal approximation and Romberg integration are very useful to compute most one-dimensional integrals with well-behaved integrands. These algorithms are discussed in more detail in Chapter 4 of "Numerical Recipes":
§4.2 Elementary Algorithms
discusses the extended trapezoid and Simpson rules, and
§4.3 Romberg Integration
discusses how to improve the trapezoid rule using Neville extrapolation
to zero step size.
// Integ.java
import comphys.*;
public class Integ {
// compute integral of f(x) form x = a to x = b
// using rectangular approximation
double f (double x) {
return Math.cos(x);
}
double a; // lower limit
double b; // upper limit
int n; // number of intervals
double dx;
double delta;
double sum;
void initial () {
a = Console.readDouble("lower limit a = ");
b = Console.readDouble("upper limit b = ");
n = 2; // initial number of intervals
dx = (b - a) / n;
delta = dx; // delta = dx only for n = 2
sum = f(a); // -> (f(a) + f(b))/2 for trapezoid rule
System.out.println();
System.out.println(" n\trectangular approximation");
System.out.println();
}
void sumf () {
double x = a + dx;
while (x < b) {
sum += f(x);
x += delta;
}
}
void doubleIntervals () { // can't use double which is a keyword!
// double the number of intervals
delta = dx;
n *= 2;
dx /= 2;
}
void output () {
System.out.println(n + "\t" + Easy.format(sum * dx, 8));
}
public static void main (String[] args) {
int doublings = 4;
if (args.length > 0)
doublings = Integer.parseInt(args[0]);
Integ integ = new Integ();
integ.initial();
do {
for (int i = 0; i < doublings; i++) {
integ.sumf();
integ.output();
integ.doubleIntervals();
}
} while (Console.getYes("continue " + doublings + " more doublings"));
}
}
Note that the True Basic program allows the calculation to continue
for ever until the user hits a key. This can be done in Java using
threads, but here we use a simpler solution: the
Console.getYes()
method asks whether you want to contiue the calculation; if you enter yes
or hit the return key the do - while loop continues, but if you enter
anything else the loop exits. The program also allows you to enter the
number of automatic interval doublings on the command line.
If you are worried that Java might be too slow for your numerical analysis applications, try a Fortran version of PROGRAM integ translated as Integ.f on your computer system!
An algorithm, such as the trapezoid rule, which uses a regular lattice of points cannot easily be extended to multidimensional integrals for two reasons: