C++ 使用Simpsons复合规则计算二重积分

C++ 使用Simpsons复合规则计算二重积分,c++,integral,numerical-integration,C++,Integral,Numerical Integration,我以前使用辛普森组合规则创建了这段代码来计算积分,现在需要修改它来计算二重积分。有人知道怎么做吗?如蒙帮助,我将不胜感激 #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 o

我以前使用辛普森组合规则创建了这段代码来计算积分,现在需要修改它来计算二重积分。有人知道怎么做吗?如蒙帮助,我将不胜感激

#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;
#包括
#包括
使用名称空间std;
浮点数f(浮点数x)//返回我们正在集成的函数
无效辛普森规则(浮点a、浮点b、整数n);//执行辛普森组合规则
int main()
{

不幸的是,辛普森规则不能直接应用于多重积分。你需要做的是分别推导二重积分或三重积分的插值曲面或超曲面。对于二重积分,你最终在九个点的网格上计算函数,而不是在单积分情况下使用的三个点。Fo三重积分你使用一个27点的三维晶格,不用说,它变得相当复杂


一种更简单的方法是,对函数进行多次随机采样,取所有函数样本的平均值,然后乘以积分面积。这里的缺点是误差与样本数的平方根成反比,因此4倍的样本数只能使预期误差减半如果您有足够的时间,并且您的精度要求不是很高,那么这可能是您应该尝试的方法。

感谢您的帮助,我将尝试一下。如果有人仍然感兴趣,可以在此处找到一个如何做到这一点的示例。()