Problem with for loop

3 visualizaciones (últimos 30 días)
Alvaro García
Alvaro García el 27 de Mayo de 2015
Comentada: Alvaro García el 28 de Mayo de 2015
areaneeded=3.75*100.1/100;
%disp(areaneeded) %area needed for a 0.1% error
a=1;
b=2;
for n=1:100;
h=(b-a)/n;
x=a:h:b;
y=x.^3;
ya=a.^3;
yb=b.^3;
area = h/2*(ya+yb+2*(sum(y)-ya-yb));
%disp(area)
tol=1e-12;
if abs(areaneeded-area)<tol
disp(n)
break
end
end
%
In this code i'm trying to find out the number of strips necessary to get an error of 0.1% with the trapezium rule. by cross multiplication i get the area i need to get with the trapezium rule, and then with the for loop i try to run n a hundred times (n=1, n=2, n=3...) and when the result from the trapezium rule is equal to the areaneeded display n. But i don't get any answer and i don't know how to solve it. Some help would be appreciate. Thanks in advance.
  2 comentarios
per isakson
per isakson el 27 de Mayo de 2015
Editada: per isakson el 27 de Mayo de 2015
Here your code runs without throwing any error. What error do you get?
Alvaro García
Alvaro García el 28 de Mayo de 2015
There was some kind of typing mistake on my code, now i dont get error but still i dont get any answers. Thanks in advance.

Iniciar sesión para comentar.

Respuesta aceptada

Roger Stafford
Roger Stafford el 27 de Mayo de 2015
You have interpreted the phrase "get an error of 0.01%" far too literally. What is clearly meant is to find the smallest n such that the error is LESS than .01 percent of the correct amount. That means that you should write
areaneeded = 3.75; % The correct amount
....
tol = 3.75*.0001; % This is .01 percent of the correct amount
....
if abs(areaneeded-area) < tol
break;
As your code stands, the value n = 44 gets too much error and the next value n = 45 gets too little error to satisfy the tol = 1e-12 inequality which is a very tight requirement. Your code will never break.
  1 comentario
Alvaro García
Alvaro García el 28 de Mayo de 2015
Thanks, i didnt notice that. Thanks a lot!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Get Started with MuPAD en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by