Listing 2. The Simpson's Rule Class
public class SimpsonsRule
{
private double a; // the lower limit of the integration
private double b; // the upper limit of the integration
private int n; // the number of points for the integration
public SimpsonsRule()
{
setA(0);
setB(1);
setN(10);
}
public SimpsonsRule(double a,double b,int n)
{
setA(a);
setB(b);
setN(n);
}
public double integrate()
{
int n = getN();
if(!isEven(n))
setN(++n);
double[] endpoints = getEndpoints();
double h = calcH(endpoints[0],endpoints[1],n);
double area = calcArea(n,h);
return area;
}
private double getA()
{
return a;
}
private void setA(double a)
{
this.a = a;
}
private double getB()
{
return b;
}
private void setB(double b)
{
this.b = b;
}
private int getN()
{
return n;
}
private void setN(int n)
{
this.n = n;
}
private double[] getEndpoints()
{
double[] endpoints =
{
getA(),
getB(),
};
return endpoints;
}
private double calcH(double a,double b,int n)
{
return (a + b) / (double)n;
}
private double calcArea(int n,double h)
{
double xi = 0.0;
double area = 0.0;
double factor = h / 3D;
for(int i = 0;i <= n;++i)
{
xi = calcXi(i,h);
if(i == 0 || i == n)
area += calcFunction(xi);
else if(isEven(i))
area += 2D * calcFunction(xi);
else
area += 4D * calcFunction(xi);
}
return factor * area;
}
private double calcXi(int i,double h)
{
return getA() + i * h;
}
private double calcFunction(double x)
{
return Math.sin(x);
}
private boolean isEven(int n)
{
if(n % 2 == 0)
return true;
else
return false;
}
}
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.