复合梯形算法流程图
复合Simpson算法流程图
龙贝格算法流程图
代码:
/*复合梯形*/
#include <stdio.h>
#include <math.h>
#define EPS 0.5e-7
// 定义被积函数
double f(double x) {
return (-2.0/(x*x-1));
}
// 复合梯形公式
double trapezoidal(double a, double b, int n) {
double h = (b - a) / n;//步长
double sum = (f(a) + f(b)) / 2.0;
for (int i = 1; i < n; i++) {
double x = a + i * h;
sum += f(x);
}
return h * sum;
}
int main() {
double a = 2, b = 3; // 积分区间
int n = 20; // 将区间分为n个小区间
double result = trapezoidal(a, b, n);
//输出近似解
printf("The result is: %lf\n", result);
//输出精确解
printf("The exact value is %lf", log(2)-log(3));
return 0;
}
/*复合Simpson*/
#include <stdio.h>
#include <math.h>
#define EPS 0.5e-7
// 定义被积函数
double f(double x) {
return (-2.0/(x*x-1));
}
// 复合Simpson公式
double simpson(double a, double b, int n) {
double h = (b - a) / n;
double sum = f(a) + f(b);
for (int i = 1; i < n; i++) {
double x = a + i * h;
if (i % 2 == 0) {
sum += 2.0 * f(x);
} else {
sum += 4.0 * f(x);
}
}
return h * sum / 3.0;
}
int main() {
double a = 2,b = 3; // 积分区间
int n = 20; // 将区间分为n个小区间
double result = simpson(a, b, n);
//输出近似解
printf("The result is: %lf\n", result);
//输出精确解
printf("The exact value is %lf", log(2)-log(3));
return 0;
}
//
/*龙贝格*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define EPS 0.5e-7
double f(double x)
{
double f1;
if(x != 0) f1=(-2.0 / (x*x-1));
return f1;
}
void rom(double a, double b)
{
double h, s1, c1, r1, s2, c2, r2, t1, t2, s;
int i, k, n;
h=(b - a) / 2;
t2=(f(a) + f(b)) * h;
s2 = 0;
c2 = 0;
r2 = 0;
n = 1;
k = 0;
do{
//循环求r2
t1 = t2;
s1 = s2;
c1 = c2;
r1 = r2;
s = 0.0;
for(i = 1; i <= n; i++)
{
s = s + f(a + (2*i - 1) * h);
}
//分别计算t2,s2,c2,r2(套公式)
t2 = t1/2 + s*h;
s2 = (4*t2 - t1) / 3;
c2 = (16*s2 - s1) / 15;
r2 = (64*c2 - c1) / 63;
n = n*2;
k = k+1;
h = h/2;
//输出近似解
printf("R(%d) = %.9lf\n", k, r2);
}while(fabs(r2-r1) >= EPS);
//输出精确解
printf("\nThe exact value is %lf", log(2)-log(3));
}
int main()
{
double a, b;//积分区间
a=2;
b=3;
rom(a, b);
}