數值積分 by simpson's rule
(高顯忠, sjgau4311@gmail.com, 2011-04-19 15:23)
1樓
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <time.h>
#include <math.h>
using namespace std;
// --------------------------------------------------------
#define pi (4.0*atan(1.0))
// --------------------------------------------------------
int main(int argc, char *argv[])
{
// plot y= sin(x), x= 0.0 to pi step dx
// dx= (pi - 0.0)/no, no= 16
// by Simpson's rule
// http://en.wikipedia.org/wiki/Simpson's_rule
double x1, x2, dx, x, y, px[20], py[20], sum;
int no, ct;
x1= 0.0; x2= pi;
no= 16;
dx= (x2 - x1)/no;
// for x= x1 to x2 step dx
x= x1;
x2= x2 + (dx/10);// 因為 浮點數的運算誤差,所以。。。
ct= -1;
while (x < x2) {
y= sin(x);
px[++ct]= x;
py[ct]= y;
x+= dx;
}
sum= 0.0;
for (no=0;no<=(ct-2);no+= 2) {
sum= sum + py[no] + py[no+1]*4 + py[no+2];
}
sum= sum*(1.0/3.0)*dx;
// *** http://en.wikipedia.org/wiki/Simpson's_rule
printf("\n sum= %.8lf \n", sum);
system("pause");
return 0;
}// end of main()