Calculate improper integrals using while loop

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!

 Respuesta aceptada

Jane Kim
Jane Kim el 14 de Oct. de 2014
Editada: Jane Kim el 14 de Oct. de 2014

0 votos

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.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.

Preguntada:

el 13 de Oct. de 2014

Editada:

el 14 de Oct. de 2014

Community Treasure Hunt

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

Start Hunting!

Translated by