Python Programming: An Introduction to Computer Science

(Nora) #1
158 CHAPTER10. DEFININGCLASSES

Thesituationfortheverticalcomponentis slightlymorecomplicated,sincegravitycausesthey-velocity
tochangeover time.Eachsecond,yvelmustdecreaseby9.8meterspersecond,theaccelerationofgravity.
In0.1secondsthevelocitywilldecreaseby 0 1


9 8  0 98 meterspersecond.Thenew velocityat theend
oftheinterval is calculatedas


yvel1 = yvel- time * 9.8

To calculatehowfarthecannonballtravelsduringthisinterval,weneedtoknowitsaveragevertical
velocity. Sincetheaccelerationduetogravityis constant,theaveragevelocitywilljustbetheaverageofthe
startingandendingvelocities:(yvel+yvel1)/2.0. Multiplyingthisaveragevelocitybytheamountof
timeintheinterval givesusthechangeinheight.


Hereis thecompletedloop:

while yvel >= 0.0:
xpos = xpos + time* xvel
yvel1 = yvel- time * 9.8
ypos = ypos + time* (yvel + yvel1)/2.0
yvel = yvel1

Noticehow thevelocityat theendofthetimeinterval is firststoredinthetemporaryvariableyvel1. Thisis
donetopreserve theinitialyvelsothattheaveragevelocitycanbecomputedfromthetwo values.Finally,
thevalueofyvelis assigneditsvalueat theendoftheloop.Thisrepresentsthecorrectverticalvelocityof
thecannonballat theendoftheinterval.


Thelaststepofourprogramsimplyoutputsthedistancetraveled.Addingthisstepgivesusthecomplete
program.


cball1.py


from math import pi, sin,cos


def main():
angle = input("Enterthe launch angle (in degrees): ")
vel = input("Enterthe initial velocity (in meters/sec): ")
h0 = input("Enterthe initial height (in meters): ")
time = input("Enterthe time interval between position calculations:")


# convert angleto radians
theta = (angle* pi)/180.0

# set the intialposition and velocities in x and y directions
xpos = 0
ypos = h0
xvel = vel * cos(theta)
yvel = vel * sin(theta)

# loop until the ballhits the ground
while ypos >= 0:
# calculateposition and velocity in time seconds
xpos = xpos+ time * xvel
yvel1 = yvel- time * 9.8
ypos = ypos+ time * (yvel + yvel1)/2.0
yvel = yvel1

print "\nDistancetraveled: %0.1f meters." % (xpos)
Free download pdf