Information Technology Reference
In-Depth Information
{
double h = (b-a)/((double)n);
double s = 0;
double x = a;
int i;
for (i = 1; i <= n-1; i++) {
x=x+h;
s=s+f.f(x);
}
s = 0.5 * (f.f(a) + f.f(b)) + s;
return h * s;
}
}
The integrate method is very similar to Algorithm 6.2 and the implementations
in most other languages. Java is statically typed and much of the syntax is inspired
by C and C CC . Calling f.x/ is a bit different than in Fortran and C/C CC , because
we need to pass f as an object of type Func to class Trapezoidal 's integrate
method. To evaluate f , we call the f method in class Func . An actual function to
be integrated must be implemented as a method f in a subclass of Func .Hereisan
example:
class f1 implements Func {
public double f (double x)
{ return Math.exp(-x * x) * Math.log(1+x * Math.sin(x)); }
}
That is, to send a function f.x/ as an argument we actually need to implement the
function as a class and make use of object-oriented programming. Many readers
will find the Java code unnecessarily comprehensive in simple numerical problems
because of this fact.
A main program in Java is actually a method main in some class, here a test class
called Demo :
class Demo {
public static void main (String argv[])
{
double a = 0;
double b = 2;
int n = 1000;
double result = 0;
int i;
f1 f = new f1();
//f2 f = new f2();
for (i = 1; i <= 10000; i++) {
result = Trapezoidal.integrate(a, b, f, n);
}
System.out.println(result);
}
}
Since integrate is a static method in the Trapezoidal class, we can call the
method without creating an object of type Trapezoidal .Topassthe f.x/ function
defined in the f method in class f1 , we must create an object of type f1 and pass
it to the integrate method. When developing larger computer applications, the
idea of encapsulating everything in classes helps to modularize the code and ease
Search WWH ::




Custom Search