I've created a simple simpson_adaptive method that uses my own simpson method. My simpson method is correct, but my adaptive method does not seem to work for
我创建了一个简单的simpson_adaptive方法,它使用我自己的simpson方法。我的simpson方法是正确的,但是我的自适应方法似乎并不适用
integral( sin(2*pi*x)² ) ranging from -1 to 1
The following code represents the adaptive simpson method. The parameters stand for the function, [a,b] being the interval for the integral and e being the precision.
下面的代码表示自适应的simpson方法。参数表示函数,[a,b]为积分区间,e为精度。
function I = simpson_adaptief(f,a,b,e)
I1 = simpson(f,a,b,2);
I2 = simpson(f,a,b,4);
if (abs(I1-I2)<e)
I = I2;
else
I = simpson_adaptief(f,a,(a+b)/2,e) + simpson_adaptief(f,(a+b)/2,b,e);
end
end
n here being the amount of parts the function is being split into.
这里的n是函数被分割成的部分的数量。
function I = simpson(f,a,b,n)
h = (b-a)/(n);
p=0;
q=0;
for k=1:2:(n-1)
x=a+h*k;
p=p+f(x);
end
for k=2:2:(n-1)
x=a+h*k;
q=q+f(x);
end
I = h/3*(f(a)+f(b)+4*p+2*q);
end
Do you guys have any suggestions on what the possible cause of the problem could be? Other functions seem to work.
你们对这个问题的可能原因有什么建议吗?其他功能似乎也起作用。
EDIT: I think it has something to do with my if abs(I1-I2)<e
. When I change it to abs(I1-I2)>e
, it works, as my program then does the recursion step first.
编辑:我认为这与我的if abs(I1-I2)
Thanks in advance!
提前谢谢!
1 个解决方案
#1
-1
I'm pretty new to matlab, but is it possible to call for the function you are creating inside that same function file? That is what I see in your simpson_adaptief function
我对matlab很熟悉,但是可以调用在同一个函数文件中创建的函数吗?这就是我在simpson_adaptief函数中看到的
#1
-1
I'm pretty new to matlab, but is it possible to call for the function you are creating inside that same function file? That is what I see in your simpson_adaptief function
我对matlab很熟悉,但是可以调用在同一个函数文件中创建的函数吗?这就是我在simpson_adaptief函数中看到的