Langfao Langfao - 11 days ago 6
Python Question

Python: List's first term does not start at 0

So I'm trying to make a code that simulates free fall its almost all done except that the code starts at '1' instead of '0'. My code is:

def simulateFreeFall(mass,deltaT,simulationTime):
acceleration = 9.81
velocity = 0
length = 0
velocity1 = 0
length1 = 0
times = []
l = []
v = []
a = []
x = 0
timeStep = simulationTime / deltaT
while x < timeStep:
elapsedTime = deltaT * x
Dvelocity = acceleration * deltaT
velocity1 = Dvelocity + velocity
velocity = velocity1
v.append(velocity1)
a.append(acceleration)
Dlength = velocity1 * deltaT
length1 = Dlength + length
length = length1
l.append(length1)
times.append(elapsedTime)
x += 1
plt.plot(times, l, 'rs')
plt.title("Free Fall - No Friction")
plt.xlabel("Time")
plt.ylabel("Fall Length")
plt.grid(True)
plt.show()
print(l[0])

simulateFreeFall(70,0.01,60)


When I run the code the first length in the list " l " is 0.000981 instead of 0 I'm not sure what I did wrong for it to start at technically what is supposed to be after 0.01 seconds.

Answer

You could use some prints to debug this. By using print along the flow you can see what is happening.

Nothing surprising is happening, l[0] is:

l[0] = length1 = Dlength + length = velocity1 * deltaT + lenght = 
= (Dvelocity + velocity ) * deltaT + lenght 

and the key thing is that

Dvelocity = acceleration * deltaT

which are non-zero

Comments