aboutsummaryrefslogtreecommitdiff
path: root/examples/FallingBall2.jl
blob: 535af6dc9a43ecb236d85aa1ad83bc68f184374a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/Applications/Julia-1.8.app/Contents/Resources/julia/bin/julia

using Plots # for plotting trajectory

g = 9.8 # acceleration of gravity in m/s^2

dt = 0.01 # time step in seconds
t_final = 1.0 # final time of trajectory

steps = Int64(t_final/dt) # number of time steps

y = zeros(steps+1) # initial array of heights in meters
v = zeros(steps+1) # initial array of velocities in m/s

function dynamics!(y, v, t::Float64) # ! notation tells us that arguments will be modified
   for i in 1:steps
      y[i+1] = y[i] + v[i] * dt 
      v[i+1] = v[i] - g * dt
      #y[i+1] = y[i] + 0.5 * (v[i] + v[i+1]) * dt
      t = t + dt
   end

   return t
end

y0 = 10.0 # initial position in meters
v0 = 0.0 # initial velocity in m/s

y[1] = y0
v[1] = v0
t = dynamics!(y, v, 0.0) # evolve forward in time

println("\n\t Results")
println("final time  = ", t)
println("y = ", y[steps+1], " and v = ", v[steps+1])
println("exact v = ", v0 - g * t)
println("exact y = ", y0 + v0 * t - 0.5 * g * t^2.0)

plot(y) # plot position as a function of time

# energy = g * y + 0.5 * v .* v # here the mass = 1
# println("initial energy = ", energy[1])
# println("final energy = ", energy[steps+1])
# plot(energy)