I don't understand the syntax of adding tuples whose elements are also elements of a list to another list that encompasses all of the information.
I'm trying to create a trajectory list that contains tuples of flight data of a projectile during flight. I want to use tuples so that I can see all of the information for each moment in time.
import random
import math
gg = -9.81 # gravity m/s**2
tt = 10 **-9 # seconds
wind = random.randint(-10,10) # m/s
#position
x=random.randint(0,100) # m/s
#projectile
v0 = float(raw_input('Enter the initial velocity (m/s) -> '));
theta = float(raw_input('Enter the initial launch angle of projectile (degrees) -> '));
theta *= (180/3.14159265359)
xx = [x]
yy = [.000000000000000000001]
dz =[v0]
time = [0];
data = ( time, xx, yy, dz)
traj = [data]
while yy[-1] >0:
traj.append ( math.sqrt( (traj[-1][3][-1] * math.sin(theta) + gg * tt)** 2+ (traj[-1][4] * math.cos(theta) -wind) ** 2 )) # velocity
traj.append ( traj[-1][2][-1] + dz[-1] * math.sin(theta) * tt + .5* gg * tt) # y position
traj.append ( traj[-1][1][-1] * dz[-1] * math.cos(theta) - wind * tt) # x position
traj.append ( traj[-1][0][-1] + tt) # time
print traj
Edit: I would input integers for the initial angle and velocity (ie-45,45). Expected outputs would be a list of tuples containing four elements corresponding to the time, x coordinate, y coordinate, and velocity, respectively. Currently, I'm receiving a tuple index out of range error.
Where you have
traj[-1][4]
in your first traj.append
line, traj[-1]
is data
, and data
is only four elements long, so the last item is at index 3.
The problem with your code is that you append data the values you compute in the while loop to the traj
list. This will not update the lists xx
, yy
, time
or dz
. You could modify the code in the following way
while yy[-1] > 0:
dz_next = math.sqrt( (yy[-1] * math.sin(theta) + gg * tt)** 2+(dz[-1] * math.cos(theta) -wind)** 2)
yy_next = yy[-1] + dz[-1] * math.sin(theta) * tt + .5* gg * tt
xx_next = xx[-1] * dz[-1] * math.cos(theta) - wind * tt
dz.append(dz_next) # velocity
yy.append(yy_next) # y position
xx.append(xx_next) # x position
time.append(time[-1] + tt) # time
I think a better way would be the following
data = ( 0, x, 1e-20, v0) # initial data
traj = [data]
while True:
t, x, y, v = traj[-1]
if y < 0:
break
traj.append((t + tt, # time
x * v * math.cos(theta) - wind * tt, # x position
y + v * math.sin(theta) * tt + .5* gg * tt, # y position
(y* math.sin(theta) + gg * tt)** 2 + (v*math.cos(theta) -wind) ** 2) # velocity
)
print traj
t_traj, x_traj, y_traj, z_traj = zip(*traj)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.