10.2. EXAMPLEPROGRAM:CANNONBALL 157
h0 = input("Enterthe initial height (in meters): ")
time = input("Enterthe time interval between position calculations:")
Calculatingtheinitialpositionforthecannonballis alsoeasy. It willstartatdistance0 andheighth0.
We justneeda coupleassignmentstatements.
xpos = 0.0
ypos = h0
Nextweneedtocalculatethexandycomponentsoftheinitialvelocity. We’ll needa littlehigh-school
trigonometry. (See,they toldyouyou’d usethatsomeday.) If weconsidertheinitialvelocityasconsistingof
someamountofchangeinyandandsomeamountofchangeinx, thenthesethreecomponents(velocity, x-
velocityandy-velocity)forma righttriangle.Figure10.1illustratesthesituation.If weknow themagnitude
ofthevelocityandthelaunchangle(labeledtheta, becausetheGreekletterθis oftenusedasthemeasure
ofangles),wecaneasilycalculatethemagnitudeofxvelbytheequationxvel velocitycostheta. A similar
formula(usingsintheta) providesyvel.
velocity yvel = velocity * sin(theta)
theta
xvel = velocity * cos(theta)
Figure10.1:Findingthex andy componentsofvelocity.
Evenif youdon’t completelyunderstandthetrigonometry, theimportantthingis thatwecantranslate
theseformulasintoPythoncode.There’s stillonesubtleissuetoconsider. Ourinputangleis indegrees,and
thePythonmathlibraryusesradianmeasures.We’ll have to convertouranglebeforeapplyingtheformulas.
Thereare 2 πradiansina circle(360degrees);sotheta π
angle
180. Thesethreeformulasgive usthecodefor
computingtheinitialvelocities:
theta = math.pi * angle/ 180.0
xvel = velocity * math.cos(theta)
yvel = velocity * math.sin(theta)
Thatbringsustothemainloopinourprogram.We wanttokeepupdatingthepositionandvelocityof
thecannonballuntilit reachestheground.We candothisbyexaminingthevalueofypos.
while ypos >= 0.0:
I used
astherelationshipsothatwecanstartwiththecannonballontheground(=0)andstillgetthe
loopgoing.Theloopwillquitassoonasthevalueofyposdipsjustbelow 0,indicatingthecannonballhas
embeddeditselfslightlyintheground.
Nowwearrive atthecruxofthesimulation.Eachtimewegothroughtheloop,wewanttoupdatethe
stateofthecannonballtomove ittimesecondsfartherinitsflight.Let’s startbyconsideringmovementin
thehorizontaldirection.Sinceourspecificationsaysthatwecanignorewindresistance,thehorizontalspeed
ofthecannonballwillremainconstantandis givenbythevalueofxvel.
Asa concreteexample,supposetheballis travelingat 30 meterspersecondandis currently 50 meters
fromthefiringpoint.Inanothersecond,it willgo 30 moremetersandbe 80 metersfromthefiringpoint.If
theinterval is only0.1second(ratherthana fullsecond),thenthecannonballwillonlyflyanother 0 1 30 3
metersandbeat a distanceof 53 meters.Youcanseethatthenew distancetraveledis alwaysgivenbytime
- xvel. To updatethehorizontalposition,weneedjustonestatement.
xpos = xpos + time* xvel