首页 > 解决方案 > C++ 中未指定参数的数值积分

问题描述

我已经编写了一个简单的代码来用中点和梯形规则数值计算积分。它工作正常,但现在我想对其进行修改,以便它可以计算相同的积分但使用未指定的参数。因此,我想计算 e^(-\alpha*x^2) 的积分,而不是 e^(-x^2) 的积分。但是,我被困在这里。我试图只声明一个新的双阿尔法而不初始化它,但这显然让我无处可去。有没有办法在 C++ 中做这样的事情?先感谢您。

//=============================================================
// A simple program to numerically integrate a Gaussian over
// the interval a to b
//=============================================================

#include <iostream>
#include <cmath>

using namespace std;

// function implementing the midpoint rule
double midpoint(double a, double b, int n){
    double sum = 0.0;
    double width = (b-a)/n;
    for (int i = 1; i < n; i++){
        sum += exp((-1)*(a+(i+0.5)*width)*(a+(i+0.5)*width))*width;
    }
    return sum;
}

//function implementing the trapezoidal rule
double trapezoidal(double a, double b, int n){
    double width = (b-a)/n;
    double sum = (width/2)*(exp(-a*a)+exp(-b*b));
    for (int i = 1; i < n; i++){
        sum += 2*exp((-1)*(a+i*width)*(a+i*width))*width/2;
    }
    return sum;
}


int main(){
    cout << "THIS IS A SIMPLE PROGRAM TO INTEGRATE A GAUSSIAN OVER A CERTAIN INTERVAL." << endl;
    int n;
    double a, b;
    cout << "Enter the lower and upper limit of integration as doubles" << endl;
    cin >> a >> b;
    cout << "Enter the number of partitions" << endl;
    cin >> n;
    double actual = 0.886207;
    double midRule = midpoint(a,b,n);
    double trapRule = trapezoidal(a,b,n);
    cout << "For the function e^(-x^2) integrated from "<< a << " to " << b <<  endl;
    cout << "The analytic value of the integral is: " << actual << endl;
    cout << "The midpoint value of the integral for " << n << " partitions is: " << midRule << endl;
    cout << "The trapezoidal value of the integral for " << n << " partitions is: " << trapRule << endl;
    cout << "The percent error for the midpoint is: " << (abs(actual-midRule)/actual)*100 << "%" << endl;
    cout << "The percent error for the trapezoidal is: " << (abs(actual-trapRule)/actual)*100 << "%" << endl;
    return 0;
}

标签: numerical-integration

解决方案


推荐阅读