Calculate improper integrals using while loop

3 views (last 30 days)
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!

Accepted Answer

Jane Kim
Jane Kim on 14 Oct 2014
Edited: Jane Kim on 14 Oct 2014
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.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!