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!
댓글 수: 0
채택된 답변
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
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!