[英]Composite simpson rule code keep getting wrong output?
Algorthim: enter image description here算法:在此处输入图像描述
I am trying to implement this composite Simpson rule that will calculate the following integral: 1/sqrt(x) which should result in: 2我正在尝试实现这个复合辛普森规则,它将计算以下积分:1/sqrt(x) 这应该导致:2
However, I keep getting the wrong output such as 1.61663但是,我不断收到错误的输出,例如 1.61663
#include <cmath>
#include <iostream>
using namespace std;
double f(double n)
{
return 1/sqrt(n);
}
double simpson(double a, double b, double n)
{
double x0=f(a)+f(b);
double h=(b-a)/(n);
double x1=0,x2=0;
double x=0;
for(int i = 1 ; i <n;i++){
x=a+(i*h);
if(i%2==0)
{
x2=x2+f(x);
}
else
{
x1=x1+f(x);
}
}
x1=(h*(x0+2*x2+4*x1))/3;
return x1;
}
int main(){
cout<<"Integral is: "<<" "<<simpson(0.0004,1,20)<<" "<<endl;
}
The problem is not in your code, but in the function you're trying to integrate.问题不在于您的代码,而在于您尝试集成的功能。 This function diverges to infinity as
x
goes to zero.当
x
变为零时,此函数发散到无穷大。 The derivatives also diverge.衍生品也有分歧。
For the interval [a, 1]
with small a
, the error term is bounded by O[1/(N^4 a^4.5)]
.对于间隔
[a, 1]
具有小a
,误差项为界O[1/(N^4 a^4.5)]
。 That's why to calculate the integral over this interval, the grid should be very dense to get a reasonable error bound.这就是为什么要计算这个区间的积分,网格应该非常密集以获得合理的误差界限。
simpson(0.0004, 1, N)
produces the following values: simpson(0.0004, 1, N)
产生以下值:
N Result Error
--------------------------------
20 2.549041009 0.5890
200 1.986462457 0.0265
2000 1.960181808 1.8181e-4
20000 1.960000049 4.9374e-8
200000 1.960000000 5.0810e-12
And indeed, for large N
we are getting closer and closer to the exact value 1.96
with the error O(1/N^4)
.事实上,对于大
N
我们越来越接近精确值1.96
,误差为O(1/N^4)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.