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

21 views (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 13 Dec 2018
Edited: Stephen23 on 14 Dec 2018
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 Comments
Stephen23
Stephen23 on 14 Dec 2018
Orestis Stylianou's "Answer" moved here:
Yes, you are right. Thanks for the help!
Stephen23
Stephen23 on 14 Dec 2018
Edited: Stephen23 on 14 Dec 2018
@Orestis Stylianou: I hope that it helped. Please remember to accept my answer!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!