if + for loops vs while loop. Same good different results

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

 采纳的回答

Stephen23
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 个评论

Orestis Stylianou's "Answer" moved here:
Yes, you are right. Thanks for the help!
@Orestis Stylianou: I hope that it helped. Please remember to accept my answer!

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by