在这个程序中,我一直在使用Python,其目标是在给定的初始速度,角度以及结构的距离/我们的目标高度上获取用户输入。我已经能够计算到某个目标到达目标所需的时间,但我不确定为什么最终速度(到达目标时的速度)出现错误。
# User inputs
velocity = float(input('Give me a velocity to fire at (in m/s): '))
angle = float(input('Give me an angle to fire at: '))
distance = float(input('Give me how far away you are from the
structure: '))
height = float(input('Give me the height of the structure (in meters):
'))
slingshot = 5 #Height of slingshot in meters
gravity = 9.8 #Earth gravity
# Converting angles to radians
angleRad = math.radians(angle)
# Computing our x and y coordinate
x = math.cos(angleRad)
y = math.sin(angleRad)
# Calculations
time = distance/(velocity * x)
vx = x
vy = y + (-9.8 * time)
finalVelocity = math.sqrt((vx ** 2) + (vy ** 2))
# Output of program
print('It takes your bird' , time , 'seconds to reach the structure')
print('Your velocity at the target distance is' , finalVelocity ,
'meters per second.')
以下是一个示例输入以及预期输出应该是什么:
输入速度:20 输入角度:40 输入距离:25 输入结构高度:15
预期输出:
到达结构的时间:1.63176 s
最终速度:15.6384秒
我的计划输出:
到达结构的时间:1.63176
最终速度:15.36755
乍一看,我的程序看起来非常接近,所以我怀疑是一个舍入错误,但它与所选数字的巧合仅仅是巧合。
答案 0 :(得分:3)
你错误估算了最终速度的horizontal and vertical components。您只使用了角度的余弦和正弦,而不是初始速度的(幅度)分别乘以余弦和正弦。如果您修改以下两行代码,根据您提供的示例输入,您将获得您要查找的结果:
vx = velocity * x
vy = velocity * y - 9.8 * time
我重写了原始代码并计算了最终高度以检查结构是否被击中,所以如果需要可以随意使用它:
import math
# User inputs
# v0 = float(input('Give me a velocity to fire at (in m/s): '))
# angle = float(input('Give me an angle to fire at: '))
# distance = float(input('Give me how far away you are from the structure: '))
# height_structure = float(input('Give me the height of the structure (in meters):'))
# Test inputs
v0 = 20
angle = 40
distance = 25
height_structure = 15
# Constants
height_slingshot = 5 # Height of slingshot in meters
g = 9.8 # Earth gravity
# Converting angle to radians
angleRad = math.radians(angle)
# Computing initial velocity components
vx0 = v0 * math.cos(angleRad)
vy0 = v0 * math.sin(angleRad)
# Computing time to travel horizontal distance
t_x = distance / vx0
# Computing final vertical velocity component
vy_final = vy0 - g * t_x
# Computing magnitude of final velocity
v_final = math.sqrt((vx0 ** 2) + (vy_final ** 2))
# Note: Horizontal component is constant
# Computing final height
y_final = height_slingshot + vy0 * t_x - g / 2 * t_x ** 2
# Verify if t_x was computed correctly
# t_y1 = (vy0 + math.sqrt(vy0 ** 2 - 2 * g * y_final)) / g
# t_y2 = (vy0 - math.sqrt(vy0 ** 2 - 2 * g * y_final)) / g
# Output of program
print('It takes your bird', t_x, 'seconds to reach the structure.')
print('Your velocity at the target distance is', v_final,
'meters per second.')
print('\nFinal height: ', y_final)
print('Structure height:', height_structure)
if 0. <= y_final <= height_structure:
print('\nYou hit the structure!')
elif y_final < 0:
print('\nYou missed. Not far enough!')
else:
print('\nYou missed. Too far!')