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

20 Ansichten (letzte 30 Tage)
Orestis Stylianou
Orestis Stylianou am 13 Dez. 2018
Bearbeitet: Stephen23 am 14 Dez. 2018
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

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by