# Python: Projectile motion of classical physics

This is a python snippet to calculate max projectile angle and distance.
It is part of test code for solving differential equation containing first and second order deviation by simple Euler method. Since I made it without reference, there may be bugs or mistakes in the code.

The projectile() calculates projectile of a mass point that is thrown from (0,0) point with initial velocity to x and y.
Because gravity g is acceleration, the g is converted into velocity by “vg += m*g * dt”. And the value is mix with current velocity to convert into position by “y0 += (vg + vy)* dt”.

import numpy as np
from matplotlib.pylab import plt
get_ipython().magic('matplotlib inline')

# dy(t)/dt = vy - gt.
# dx(t)/dt = vx.
def projectile(angle=0.3, v0=100, time=30):
t = np.linspace(0,time,300)
dt = t - t

g = -9.8
m = 1
# Distribute initial velocity to x and y.
v0 = v0
vx = v0*np.cos(angle)
vy = v0*np.sin(np.pi-angle)

y0 = 0
x0 = 0
vg = 0
y_list = [y0]
x_list = [x0]

for i in range(1, len(t)):
# Update y.
vg += m*g * dt
y0 += (vg + vy)* dt
# Update x.
x0 += vx * dt

# Stop updating when it hits ground at y=0.
if y0 > 0:
y_list.append(y0)
x_list.append(x0)
else:
break

plt.plot(x_list, y_list, label=r"$\theta$" + "=" + str(angle))
plt.legend(bbox_to_anchor=(1.3, 1.03))
# (max x, max t)
return (x_list[-1], t[len(y_list)])


The next code searches a projectile that reaches furthest point of x with changing angle.

angle = np.linspace(0, np.pi, 12)
angle = np.round(angle, 2)
max_distance = 0
max_angle = 0
max_time = 0

# Select an angle value for max distance of x.
for a in angle:
throw = projectile(a, v0=100, time=30)
if throw > max_distance:
max_distance = throw
max_angle = a
max_time = throw

print("Max Distance: " + str(max_distance) + "m")
print("Max Angle: " + str(max_angle))
print("Max Time: " + str(max_time) + "s")


The result is:
Max Distance: 1001.56788591m
Max Angle: 0.86
Max Time: 15.4515050167s

And the resulted chart is : 