Infinite Loop help Riemann sums

For some reason it's get stuck in an infinite loop. The programs says line 8 is the problem so the "first = first" line so I'm assuming its the bound problem? I don't see the problem any suggestions?
Note: my functions needs to give me an approx that has an difference from the previous estimate less than the tol that's why I'm running a while and for loop.

댓글 수: 3

Walter Roberson
Walter Roberson 2013년 2월 24일
I suggest you step through it line by line with the debugger.
Azzi Abdelmalek
Azzi Abdelmalek 2013년 2월 24일
It's difficult to say if we don not know a,b,tol and your function f.
Kenny
Kenny 2013년 2월 24일
the function is myintegral(@(x) (sin(x^2))^2,0,3,.1) but the code needs to be able to approximate any function.

댓글을 달려면 로그인하십시오.

 채택된 답변

Youssef  Khmou
Youssef Khmou 2013년 2월 24일
편집: Youssef Khmou 2013년 2월 24일

0 개 추천

hi Kenny, your program works fine for most of cases
Note : no need to declare syms x ,
I tried to to make some change according to your model , like number of samples n, no need to increase through the loop, the theorem states that the Sum converges when N->Inf :
function y = myintegralapprox(f,a,b,tol)
tol=100*tol;
n = 1000;
c = tol + 1;
first = 0;
second = 0;
counter=1;
while (c > tol)
for m=a+(((b-a)/n)/2):((b-a)/n):(b-((b-a)/n)/2)
first = first + ((b-a)/n)*(f(m));
end
counter=counter+1;
if counter>1e+6
break;
end
y = first;
c = abs(first - second);
second = first;
end
I made some tests comparing you func with "quad" function :
>>myintegralapprox(@(x) 1/(1+exp(x)),0,pi,.1)
>>quad(@(x) 1./(1+exp(x)),0,pi)
>>myintegralapprox(@(x) cos(x),0,pi,.1)
>>quad(@(x) cos(x),0,pi)
>>myintegralapprox(@(x) exp(-x^2),0,pi,.1)
>>quad(@(x) exp(-x.^2),0,pi,.1)
>>myintegralapprox(@(x) (x^3)+(x^2)+1,0,pi,1)
>>quad(@(x) (x.^3)+(x.^2)+1,0,pi)

댓글 수: 1

Kenny
Kenny 2013년 2월 24일
편집: Kenny 2013년 2월 24일
Sorry, I dont think this is the right answer. It's not giving me the right numbers according to the example :/. I answer should be 1.17501419

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Mathematics에 대해 자세히 알아보기

질문:

2013년 2월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by