使用辛普森复合规则计算双积分
Evaluate double integrals using Simpsons composite rule
我之前创建过这段代码来使用辛普森复合规则计算积分,现在需要修改它以评估双积分。有谁知道如何做到这一点?我将不胜感激任何帮助。
#include <iostream>
#include <cmath>
using namespace std;
float f(float x); //returns the function we are integrating
void simpsons_rule(float a, float b, int n); // Carries out Simpsons composite rule
int main()
{
cout << "This program finds an approximation of the integral of a function under two limits using Simpsons composite rule." << endl;
// User is introduced to program and given explanation of what it does
float a,b;
int n;
cout << "Enter the lower limit " << endl;
cin >> a;
cout << "Enter the upper limit " << endl;
cin >> b; // User has freedom to specify the upper and lower limits under which the function will be integrated
cout << "Enter the number of intervals (must be an even number) " << endl;
do
{
cin >> n; // User can also choose the number of intervals
if(n%2 == 0 && n!=0) // If an even number of intervals was entered, the program continues and simpsons rule is carried out
{
simpsons_rule(a,b,n);
}
else
{
cout << "Invalid number of intervals, please re-enter a value" << endl; //If an odd number of intervals was entered, the user is prompted to enter a valid number
}
}while(cin); // do-while loop used to ensure even number of intervals was entered
return 0;
}
float f(float x)
{
return(pow(x,4) - 3*pow(x,3) + pow(x,2) + x + 1); // function to be integrated
}
void simpsons_rule(float a, float b, int n)
{
float s2 = 0;
float s3 = 0;
int i;
float h = (b-a)/n; // step length is calculated
for(i=1; i <= (n/2)-1; i++)
{
if((i%2) == 0) // checks if i is even
{
s2 = s2 + f(a+(i*h)); // Finds the sum of all the values of f(x) where x is even
}
}
for(i=1; i<=(n/2); i++)
{
if((i%2) == 1) // checks if i is odd
{
s3 = s3 + f(a+2*(i*h)); // Finds the sum of all the values of f(x) where x is odd
}
}
float s = (h/3)*(f(a)+ f(b) + (2*s2) + (4*s3)); // This variable contains the final approximaton of the integral
cout << "The value of the integral under the specified limits is: " << s << endl;
不幸的是,辛普森规则不能直接应用于多个积分。您需要做的是分别导出双积分或三重积分的插值曲面或超曲面。对于二积分,您最终会在九个点的网格上评估函数,而不是在单积分情况下使用的三个点。对于三重积分,您使用 27 个点的三维晶格。不用说,它变得非常复杂。
一种更简单的方法是某种蒙特卡罗积分,在这种积分中,您可以多次随机抽样函数,取所有函数样本的平均值,然后乘以积分面积。这里的缺点是误差与样本数的平方根成反比,因此 4 倍的样本数只会使预期误差减半。如果您有足够的时间并且精度要求不是很好,那么这可能是您应该尝试的方法。
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 递归函数计算序列中的平方和(并输出过程)
- (C++)分析树以计算返回错误值的简单算术表达式
- 我的字符计数代码计算错误.为什么
- 在计算中使用二的幂有多有利可图
- 此代码是否违反一个定义规则
- 如何计算文件中的"columns"数?
- 计算排序向量的向量中唯一值的计数
- 如何使用 std::累积在 C++ 中计算总和立方体
- 生成文件不对文件使用隐式规则
- 使用Qt C++计算类似Git的SHA1哈希
- OpenCV C++.快速计算混淆矩阵
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- C++如何计算用户输入的数字中的偶数位数
- 如何计算数据类型的范围,例如int
- 类似枚举的计算常量
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 使用辛普森复合规则计算双积分
- 使用霍纳规则计算 Erf 函数(不使用阶乘和幂)