Python Programming: An Introduction to Computer Science

(Nora) #1
156 CHAPTER10. DEFININGCLASSES

10.2 ExampleProgram:Cannonball.


Beforelaunchingintoa detaileddiscussionofhow towriteyourownclasses,let’s take a shortdetourtosee
how usefulnew classescanbe.


10.2.1 ProgramSpecification


Supposewewanttowritea programthatsimulatestheflightofa cannonball(orany otherprojectilesuchas
a bullet,baseballorshotput).We areparticularlyinterestedinfindingouthow farthecannonballwilltravel
whenfiredat variouslaunchanglesandinitialvelocities.Theinputtotheprogramwillbethelaunchangle
(indegrees),theinitialvelocity(inmeterspersecond)andtheinitialheight(inmeters).Theoutputwillbe
thedistancethattheprojectiletravelsbeforestrikingtheground(inmeters).
If weignoretheeffectsofwindresistanceandassumethatthecannonballstaysclosetoearth’s surface
(i.e.,we’re nottryingto putit intoorbit),thisis a relativelysimpleclassicalphysicsproblem.Theacceleration
ofgravityneartheearth’s surfaceis about9.8meterspersecondpersecond.Thatmeansif anobjectis thrown
upwardat a speedof 20 meterspersecond,afteronesecondhaspassed,itsupwardspeedwillhave slowedto
20  9 8 10 2 meterspersecond.Afteranothersecond,thespeedwillbeonly 0 4 meterspersecond,and
shortlythereafterit willstartcomingbackdown.
Forthosewhoknow a littlebitofcalculus,it’s nothardtoderive a formulathatgivesthepositionofour
cannonballat any givenmomentinitsflight.Ratherthantake thecalculusapproach,however, ourprogram
willusesimulationtotrackthecannonballmomentbymoment.Usingjusta bitofsimpletrigonometryto
getstarted,alongwiththeobviousrelationshipthatthedistanceanobjecttravelsina givenamountoftime
is equaltoitsratetimestheamountoftime(d rt), wecansolve thisproblemalgorithmically.


10.2.2 DesigningtheProgram.


Let’s startbydesigininganalgorithmforthisproblem.Giventheproblemstatement,it’s clearthatweneed
toconsidertheflightofthecannonballintwo dimensions:height,soweknow whenit hitstheground,and
distance,tokeeptrackofhow farit goes.We canthinkofthepositionofthecannonballasa point


xy ina
2Dgraphwherethevalueofygivestheheightandthevalueofxgivesthedistancefromthestartingpoint.
Oursimulationwillhave to updatethepositionofthecannonballto accountforitsflight.Supposetheball
startsat position


0  0 , andwewanttocheckitsposition,say, everytenthofa second.Inthatinterval,it will
have movedsomedistanceupward(positivey) andsomedistanceforward(positivex). Theexactdistancein
eachdimensionis determinedbyitsvelocityinthatdirection.
Separatingoutthexandycomponentsofthevelocitymakestheproblemeasier. Sinceweareignoring
windresistance,thexvelocityremainsconstantfortheentireflight.However, theyvelocitychangesover
timeduetotheinfluenceofgravity. Infact,theyvelocitywillstartoutbeingpositive andthenbecome
negative asthecannonballstartsbackdown.
Giventhisanalysis,it’s prettyclearwhatoursimulationwillhave todo.Hereis a roughoutline:


Input the simulationparameters: angle, velocity, height, interval.
Calculate the initialposition of the cannonball: xpos, ypos
Calculate the initialvelocities of the cannonball: xvel, yvel
While the cannonballis still flying:
update the valuesof xpos, ypos, and yvel for interval seconds
further intothe flight
Output the distancetraveled as xpos


Let’s turnthisintoa programusingstepwiserefinement.
Thefirstlineofthealgorithmis straightforward.We justneedanappropriatesequenceofinputstate-
ments.Here’s a start:


def main():
angle = input("Enterthe launch angle (in degrees): ")
vel = input("Enterthe initial velocity (in meters/sec): ")

Free download pdf