Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 743
Kernel: Python 2 (SageMath)

For an object that is accelerating, you need to update the velocity at each time step in addition to updating the position. The easiest way to update velocity is to use the definition of acceleration:

a=vfvitfti\vec{a}=\frac{\vec{v}_f - \vec{v}_i}{t_f - t_i}vf=vi+a(tfti)\vec{v}_f = \vec{v}_i + \vec{a}(t_f - t_i)

Because of the way compute programs work, the line ball.vel = ball.vel + g*dt is equivalent to the above equation. In other words, Python calculates everything to the right of the equals sign and then assigns it to the variable to the left. This means that ball.vel on the right side is the initial velocity vi\vec{v}_i, while ball.vel on the left side is actually the final velocity vf\vec{v}_f.

Run the code below to see a ball moving with a constant gravitational force.

from vpython import * scene=canvas() #Create canvas to draw on graph_screen=graph(width=400,height=400,xtitle='time', ytitle='Position',xmin=0,xmax=3,ymin=-10,ymax=10) pos_graph = gcurve(color=color.blue, width=4) #Create curve to plot position vs. time graph_screen2=graph(width=400,height=400,xtitle='time', ytitle='Velocity', xmin=0,xmax=3,ymin=-20,ymax=10) vel_graph = gcurve(color=color.red,width=3) #Curve for velocity ground=box(pos=vector(0,-1,0),axis=vector(1,0,0),length=20,height=0.1,color=color.green) #Grass-colored box for reference ball=sphere(color=color.blue) #Create the ball ball.vel=vector(10,10,0) #Give ball a velocity attach_arrow(ball,"vel",scale=.5,color=color.yellow) #Attach an arrow to show velocity attach_trail(ball,color=color.yellow,type="points",retain=10,pps=1) g=vector(0,-9.8,0) dt=0.01 t=0 while t<300: rate(30) ball.pos=ball.pos+ball.vel*dt #update position ball.vel=ball.vel + g*dt #update velocity position=ball.pos.y #For plotting position velocity=ball.vel.y #For plotting velocity time=t*dt #For plotting pos_graph.plot(pos=(time,position)) #Plot a single data point on the graph vel_graph.plot(pos=(time,velocity)) t=t+1 #Advance time step
<IPython.core.display.Javascript object>

For You To Try

  • Add a second object with a different initial velocity

  • Add curves to both graphs for this new object and plot the y-position and y-velocity