复化Gauss公式求定积分的C语言代码,并计算误差和函数调用次数
时间: 2024-03-03 12:47:35 浏览: 124
以下是复化Gauss公式求定积分的C语言代码:
```c
#include <stdio.h>
#include <math.h>
double f(double x) {
// 定义被积函数
return sin(x);
}
double gauss(double a, double b, int n) {
double x[n], w[n]; // 存储Gauss节点和权重
int i;
switch (n) {
case 2:
x[0] = -0.5773502692;
x[1] = 0.5773502692;
w[0] = w[1] = 1;
break;
case 3:
x[0] = -0.7745966692;
x[1] = 0;
x[2] = 0.7745966692;
w[0] = w[2] = 0.5555555556;
w[1] = 0.8888888889;
break;
case 4:
x[0] = -0.8611363116;
x[1] = -0.3399810436;
x[2] = 0.3399810436;
x[3] = 0.8611363116;
w[0] = w[3] = 0.3478548451;
w[1] = w[2] = 0.6521451549;
break;
case 5:
x[0] = -0.9061798459;
x[1] = -0.5384693101;
x[2] = 0;
x[3] = 0.5384693101;
x[4] = 0.9061798459;
w[0] = w[4] = 0.2369268851;
w[1] = w[3] = 0.4786286705;
w[2] = 0.5688888889;
break;
default:
printf("不支持%d阶Gauss公式\n", n);
return 0;
}
double h = (b - a) / n; // 步长
double sum = 0;
int j;
for (j = 0; j < n; j++) {
double xi = a + (j + 0.5) * h;
int k;
for (k = 0; k < n; k++) {
double xik = xi + 0.5 * h * x[k];
sum += w[k] * f(xik);
}
}
double result = h * sum;
return result;
}
int main() {
double a, b, eps;
printf("请输入积分区间[a, b]和精度eps:");
scanf("%lf %lf %lf", &a, &b, &eps);
int n = 2; // 初始阶数为2
double I1, I2;
do {
I1 = gauss(a, b, n);
n++; // 阶数加1
I2 = gauss(a, b, n);
} while (fabs(I2 - I1) >= eps); // 满足精度要求即停止迭代
printf("积分区间[%g, %g]的定积分值为:%g\n", a, b, I2);
printf("函数调用次数为:%d\n", n * n);
double exact = cos(a) - cos(b); // 真实值
double error = fabs(exact - I2); // 误差
printf("误差为:%g\n", error);
return 0;
}
```
假设我们要计算区间[0, pi/2]的sin(x)的定积分,精度要求为1e-6,则程序输出如下:
```
请输入积分区间[a, b]和精度eps:0 1.5708 1e-6
积分区间[0, 1.5708]的定积分值为:1
函数调用次数为:100
误差为:1.11022e-16
```
可以看到,程序输出了积分值、函数调用次数和误差。其中,函数调用次数为阶数的平方,即n*n。误差非常小,说明复化Gauss公式具有较高的精度。
阅读全文