使用代码编写计算弹丸运动值的函数

时间:2017-03-03 15:13:14

标签: python

我有一个作业,要求我使用一些给定的代码来编写一个函数,该函数计算击中10米外目标所需的角度。

这是给定的代码:

from visual import *
from visual.graph import * # For the graphing functions 
#Create a graph display window (gdisplay) 

win = gdisplay(xtitle="Distance [m]", ytitle="Height [m]") 
#And a curve on this display 

poscurve = gcurve(gdisplay=win, color=color.cyan) 
#Target position (10 meters away) 

target_pos = vector(10,0,0) 
#Set the starting angle (in degrees) 

angle = 45 
#Set the magnitude of the starting velocity (in m/s) 

v0 = 12.0 
#Gravity vector (m/s**2) 

g = vector(0, -9.8, 0) 
#Create a vector for the projectile's velocity 

velocity = v0 * vector(cos(anglepi/180), sin(anglepi/180), 0) 
#and the position 

position = vector(0,0,0) 
dt = 0.01 # Time step 
#Start loop. Each time taking a small step in time 

while (position.y > 0) or (velocity.y > 0): # Change in position # dx =          (dx/dt) * dt dx = velocity * dt 
# Change in velocity 
# dv = (dv/dt) * dt 
dv = g * dt 

# Update the position and velocity 
position = position + dx 
velocity = velocity + dv 

# Plot the current position 
poscurve.plot(pos=position) 
#When loop finishes, velocity.y must be < 0, and position.y < 0 

print "Landed at X position: ", position.x print "X distance to target: ",     position.x - target_pos.x

我现在如何编写一个函数来计算所需的值?我不知道从哪里开始,任何帮助将不胜感激!

由于

1 个答案:

答案 0 :(得分:0)

您可以使用数学计算出结果的等式。

这可以作为:

 range = 2v^2/g *cos(a)sin(a)

where v=initial velocity
a=angle
g=gravitational acceleration

您可以使用此python脚本找到答案:

from math import cos
from math import sin
from math import radians
from math import fabs

a=0 # angle in degrees
target=10  # How far you want it to go in m
v=12 # initial velocity in m/s
g=9.81 #gravitational acceleration m/s/s

best_angle=None
nearest_answer=None

while a<45: # we only need to check up to 45 degrees
    r = 2*v*v/g*cos(radians(a))*sin(radians(a))
    if not nearest_answer or fabs(r-target)<fabs(nearest_answer-target):
        nearest_answer = r
        best_angle = a
    print("{0} -> {1}".format(a,r))
    a+=.1 # try increasing the angle a bit. The lower this is the more accurate the answer will be

print("Best angle={}".format(best_angle))