numerical-integration - 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;
}
解决方案
推荐阅读
- swift - 使 struct init() 参数接受两种类型?
- swift - 用破折号导入模块
- macos - 如何将 MariaDB 设置为 MAMP
- reactjs - 当用户在 react-form-hooks 和 react-select 中进行不同选择时从 FormField 中删除数据
- javascript - 纱线找不到模块(html-to-text)
- ffmpeg - 尝试使用 ffplay 或 vlc 播放 h264 流时的伪影
- javascript - 有什么方法可以检测到 Ctrl + S?
- javascript - 我试图在这种情况下将一个字符放在一行中
- javascript - 通过js将URL从剪贴板传递到iframe?
- terraform - terraform : 将 var 与正则表达式和条件操作匹配