复化辛普森Simpson求积公式 c语言实现 数值积分
标签:计算方法实验
/*
本实验用复化辛普森求积公式求sinx在[1, 2]的定积分。
*/
#include <stdio.h>
#include <math.h>
double f(double x){
return sin(x);
}
double Simpson(double a, double b, int n){
double h = (b - a) / n, s1 = f(a + h / 2), s2 = 0;
for(int i = 1; i < n; i++){ //1 <= k <= n - 1
s1 += f(a + i * h + h / 2);
s2 += f(a + i * h);
}
return h * (f(a) + 4 * s1 + 2 * s2 + f(b)) / 6;
}
int main(){
int n = 8; //区间等分数
double a = 1, b = 2; //上下限
printf("answer = %f\n", Simpson(a, b, n));
return 0;
}
实验结果