if + for loops vs while loop. Same good different results
조회 수: 18 (최근 30일)
이전 댓글 표시
Hello people,
So I am doing an online course. And I am stuck in one of the problems. I have to calculate the period of a pendulum.
This is my code:
function [ T ] = pendulum( L,a0 )
g = 9.8;
a = [];
omega = 0;
theta = a0;
dt = 10^-6;
for time = 0:dt:10
a = g*sin(theta)/L;
omega = omega + a*dt;
theta = theta - omega*dt;
if theta >= 0
T = 4*time;
else
break
end
end
This is the correct answer:
function [ T ] = pendulum( L,a0 )
%PENDULUM Summary of this function goes here
% L positive scalar
% a0 positive scalar less than pi
% alpha = angluar acceleration
% g = acceleration due to gravity
% omega = angular velocity
if L <=0
fprintf('L must be a positive real number')
T=0
return
end
theta=a0;
g=9.8;
omega=0;
deltat=1e-6;
T=0;
while theta>0
T=T+deltat;
alpha=g*sin(theta)/L;
omega=omega+alpha*deltat;
theta=theta-omega*deltat;
end
T=4*T
%formula=T/(2*pi*sqrt(L/g))
end
For L = 2 and a0 = pi/2
my code gives:
3.350336000000000
the correct code gives:
3.350344000012992
So the only difference between the two codes is that I used an if loop inside a for loop and the correct loop used only a while loop. Any ideas what could be the problem?
Thanks
댓글 수: 0
채택된 답변
Stephen23
2018년 12월 13일
편집: Stephen23
2018년 12월 14일
Work backwards from the end, and look at where the time / T value last changes. They are not the same. The location of the the if and break is important, and/or the logical condition that you use.
Both of these give the same output (to within floating point tolerances):
for time = 0:dt:10
if theta<0
break
end
a = g*sin(theta)/L;
omega = omega + a*dt;
theta = theta - omega*dt;
end
T = 4*time
And
while theta>0
T=T+dt;
alpha=g*sin(theta)/L;
omega=omega+alpha*dt;
theta=theta-omega*dt;
end
T = 4*T
댓글 수: 2
Stephen23
2018년 12월 14일
Orestis Stylianou's "Answer" moved here:
Yes, you are right. Thanks for the help!
추가 답변 (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!