I am currently working on an assignment where I have to find the answer to the following integral using Simpsons rule:$\int x+1$ (MIN = -1 MAX = 3), I choose to have 6 intervals. I now start calculating: $delta X = \frac{b-a}{n} = \frac{3--1}{6} = \frac{4}{6} = 0.6666666~$ $$\frac{\frac{6}{4}}{3} (=>\frac{2}{9})*(f(0*\frac{4}{6} + 4* f(1*\frac{4}{6})+ 2* f(2*\frac{4}{6})+ 4* f(3*\frac{4}{6})+ 2* f(4*\frac{4}{6})+ 4* f(5*\frac{4}{6}) + f(6*\frac{4}{6})) = \frac{34}{3} = 11.3333$$ (The actual calculation was done by wolfram alpha)It should be 8. I wrote this into a Java funtion:
public class Simpsons_rule {
public void start(Formula f, int n) throws Exception{
if (n%2 != 0){
throw new Exception("n must be even.");
}
double deltaX = (f.getB() - f.getA())/n;
double endanswer = 0.0;
for (double interval = 1.0; interval < n ; ++interval){
if (interval%2 != 0){
endanswer += 4*(f.calculate(interval * deltaX));
} else {
endanswer += 2*(f.calculate(interval * deltaX));
}
}
endanswer += f.calculate(0); //or 0*deltaX, whichever you prefer
endanswer += f.calculate(n*deltaX));
endanswer *= deltaX/3;
System.out.println(endanswer);
}
}
The class that gets used:
public class Som3 implements Formula {
@Override
public void print() {
System.out.println("Som 3\n x+1 dx (MIN = -1 MAX = 3");
}
@Override
public double calculate(double d) {
return d+1;
}
@Override
public double getA() {
return -1;
}
@Override
public double getB() {
return 3;
}
@Override
public void printCorrectAnswer() {
System.out.println("The correct answer: 8 (Calculated by Wolfram Alpha)");
}
}
This function works perfect for any intergral that I push into it, except for this one. The only difference between these intergrals is that a is below 0 here and above or equal to zero everywhere else. Is it true that Simpsons rule only applies when a>=0? Or Am I doing something wrong?
Edit: My understanding of Simpsons rule was incorrect, here is the correct version of class Simpsons_Rule:
public class Simpsons_rule {
public void start(Formula f, int n) throws Exception{
if (n%2 != 0){
throw new Exception("n must be even.");
}
double deltaX = (f.getB() - f.getA())/n;
double endanswer = 0.0;
for (double interval = 1.0; interval < n ; ++interval){
if (interval%2 != 0){
endanswer += 4*(f.calculate(interval * deltaX + f.getA()));
} else {
endanswer += 2*(f.calculate(interval * deltaX + f.getA()));
}
}
endanswer += f.calculate(f.getA()); //or 0*deltaX, whichever you prefer
endanswer += f.calculate(f.getB());
endanswer *= deltaX/3;
System.out.println(endanswer);
}
}
I would not use a double for
interval, but regarding your question: $a<0$ is allowed, all you should require is $b>a$.However, why do you call
f.calculate(0)and notf.calculate(f.getA())? Or maybe you should callf.calculate(f.getB()-f.getA())instead off.calculate(f.getB())? It is hard to tell without knowing whatcalculatedoes. At any rate, I suspect that your method fails for many functions and intervals.