Hello,
I just joined, so if I infringe upon any of the forum rules, then I apologize. Anyway, I have a code for approximating integrals via the Simpson's Method. The problem with the code is that somewhere within the mere 52 lines, I have divided my entire sum by 2. Having seen this in the end result, I found I have to multiply the whole thing by 2 to get the right answer. I know this is redundant, and I fear that, depending where the devision is, it might make my integration approx. less accurate. If it isn't too much work, can someone find where I went wrong in my code? By the way, this is not the usual Simpson's approx. It is called the Composite Simpson's Rule; the algorithm can be found on Wikipedia: http://en.wikipedia.org/wiki/Simpson_method
Also, as a side note, how do I turn this source code into a class for an arbitrary function (not just, say, for cos(x)?)
/*
* Simprule.cpp
*
* Created on: Mar 14, 2009
* Author: keith burghardt
*/
# include <iostream>
using namespace std;
#include <cmath>
#include<iomanip>
double begin,end,area,h;
long double f(long double x){
return(//State function for integration
cos(x)
);
}
long double simps(double,double,long double,double);
int main (void){
cout<<"State beginning and end number for integration: ";
cin>>begin>>end;
long int n(1e6*int(fabs(end-begin)));//make sure n is even (must be able to divide by 2, see below)
long double h(fabs(end-begin)/n);//the fabs() are useful in making sure that, in the simpsons rule,
//I need not have 2 cases for the for loops
area=simps(begin,end,h,n);
cout<<"AREA of F(x)= "<<setprecision(19)<<area<<endl<<"Area really is "<<sin(end);//I use this to check my answer
return 0;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//composite simp rule
long double simps (double begin, double end,long double h,double n){//using simpson's rule to approx. an area
double b(begin),e(end);
if(begin>end){//needed in order to make sure that I don't have to make 2 for loops
//one for b>e, and one for e>b.
b=end;
e=begin;
}
long double sum(f(b)),sum2(0),sum4(0);
for(int i=1;i<=n/2-1;i+=2){//adding up all even points
sum2=sum2+f(b+h*(2*i));
}
for(int k=1;k<=n/2;k+=2){//adding up all odd points
sum4=sum4+f(b+h*(2*k-1));
}
sum=(2*h/3)*(sum+2*sum2+4*sum4+f(e));//!!*can't find where I divided answer*!!<----------PROBLEM!!!
if(begin>end){//needed so that if I integrate from a larger to smaller number,
sum=-sum;//the sum will be negitive
}
return(sum);
}