Calculate improper integrals using while loop

4 次查看(过去 30 天)
Hello! I need some help. I am trying to use a while loop and int to calculate the integral of f(x) over the interval [a,b] for b = a, a + 1, a + 2, ... until successive integrals differ by less than some small number. Can somebody evaluate my code and let me know where problems may be? Thanks!
Also, I'm not returning any error messages... Just not returning the correct answers.
function a = myimproperintegral(f, a, tol)
syms x;
m=0;
n=0;
b=a;
while (tol < abs(m-n))
m=int(f(x), a, b);
b=b+1;
n=int(f(x), a, b);
end
a=n;
end
Here is the sample data:
a = myimproperintegral(@(x) 1/x^2,2,0.01)
a = 0.40909090909090909090909090909091
a = myimproperintegral(@(x) -1/x^3,3,0.001)
a = -0.051423324150596877869605142332415
a = myimproperintegral(@(x) 2*exp(-x),log(3),0.02)
a = 0.66217470200060977357189425877572
a = myimproperintegral(@(x) x^(-1.1),1,0.1)
a = 1.9725843823976931790483046193628
Any advice is much appreciated!

采纳的回答

Jane Kim
Jane Kim 2014-10-14
编辑:Jane Kim 2014-10-14
All you have to do is define m and n before the while loop. Instead of equating them to 0, use what you put in the while loop to define the two variables (e.g. m=int(f(x), a, b); n=int(f(x), a, b);). Watch the value of b.
If you don't, then t-s=0 automatically, so the function isn't going to do what you want it to do.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by