数学问题:
利用Romberg算法求解定积分方程:
,eps=
解决代码:
#include<iostream>
#include<cmath>
#include<vector>
#include <math.h>
#include<iomanip>
using namespace std;
double RombergIntegral(double a, double b, double eps, int n);
double f(double x, int num);
vector < vector < double >> T; // 用于存储T表
int main()
{
string laug;
double a1, b1; double eps; int num;
cin >> laug;
cin >> a1 >> b1;
cin >> eps;
cin >> num;
cout << fixed << setprecision(6) << RombergIntegral(a1, b1, eps, num) << endl;
return 0;
}
double RombergIntegral(double a, double b, double eps, int n)
{
int k(0);
double h = b - a;
vector < double > temp;
T.push_back(temp);
T[0].push_back(h * (f(a, n) + f(b, n)) / 2);
for (k = 1; 1; ++k)
{
T.push_back(temp);
T[0].push_back(0.5 * T[0][k - 1]);
for (int i = 0; i < pow(2, k - 1); ++i)
{
T[0][k] += 0.5 * h * (f(a + h / 2 + i * h, n));
}
for (int i = 1; i <= k; ++i)
{
T[i].push_back((pow(4, i) * T[i - 1].back() - T[i - 1][k - i]) / (pow(4, i) - 1));
}
h /= 2;
double temp = T[k].back();
if (fabs(T[k].front() - T[k - 1].front()) < eps) break;
}
cout << k << endl;
return T[k].back();
}
double f(double x, int num) // 要求的积分函数
{
if (num == 1)
return pow(x, 2) * sin(1 / x);
if (num == 2)
return sin(x);
if (num == 3)
return pow(x, 3) + cos(x * x);
}
使用方法:
第一行是1个字符串,为算法函数名称:RombergIntegral
第二行是2个数字,第一个为积分下限:a,第二个为积分上限:b,a、b中间用一个空格相连(注意:如果下限为0,请改为0.0000001,上限同样)
第三行是1个精度数,为积分精度:eps
第四行是1个数,为被积函数表达式的序号:funNum
测试输入:
RombergIntegral
0.0000001 1
1e-7
1
预期输出:
13
0.286530
问题解决:
计算结果为: