如何解决C ++中带有未指定参数的数值积分
我写了一个简单的代码,用中点和梯形法则计算数值。它可以正常工作,但现在我想对其进行修改,以便它可以计算相同的积分,但参数未指定。因此,我想计算e ^(-\ alpha * x ^ 2)的积分,而不是e ^(-x ^ 2)的积分。但是,我被困在这里。我试图只声明一个新的double alpha而不初始化它,但这显然使我无处可去。有没有办法在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,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,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;
}
解决方法
您可以简单地定义一个带有默认值的全局alpha
变量:(但请参阅最后的注释)
...
#include <iostream>
#include <cmath>
using namespace std;
double alpha = 0.5; // really should use: `static double` though.
...
或者您可以在alpha
中声明main()
,并进行以下更改:
double a,b,alpha;
然后,您可以像a
和b
那样接受一个值,例如cin >> alpha;
如果在alpha
中声明main()
,则需要在midpoint
和trapezoidal
的函数参数中添加一个参数:
double midpoint (double a,double b,double alpha,int n)
// called using: double midRule = midpoint(a,alpha,n);
double trapezoidal (double a,double int n)
// called using: double trapRule = trapezoidal(a,n);
然后将sum
的表达式从(-1)
更改为:(- alpha)
如果您使用全局alpha
变量,则无需更改这些功能说明,因为这些变量已经对这些函数“可见”了-这就是 global 范围的含义。除非出于充分的理由是必要的,否则最好避免这种方法。
由于您处理alpha
的方式与其他输入变量几乎相同,因此最好在alpha
中声明main()
,然后向函数中添加参数。简而言之,没有充分的理由在此处使用 global alpha
变量。
由于在[0,+INF]
范围内的精确积分为:0.5 * sqrt(PI / alpha)
,因此可以用以下方式恢复产生积分值(r)
的'未指定'alpha':alpha = PI / (4 * r * r)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。