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 returnend 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;endT=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
Best Answer