aboutsummaryrefslogtreecommitdiff
path: root/examples/FallingBall2.jl
diff options
context:
space:
mode:
authorsotech117 <michael_foiani@brown.edu>2024-02-01 12:35:05 -0500
committersotech117 <michael_foiani@brown.edu>2024-02-01 12:35:05 -0500
commit3c7d70ebd43423220b266dab218ca6d687996d08 (patch)
treeaa4b9869ea4248858b8aee46f73da55abb22c665 /examples/FallingBall2.jl
parentadb65f3f12061e6cc8919338d28e006f7fa01c2f (diff)
pull examples and complete homework 1
Diffstat (limited to 'examples/FallingBall2.jl')
-rw-r--r--examples/FallingBall2.jl44
1 files changed, 44 insertions, 0 deletions
diff --git a/examples/FallingBall2.jl b/examples/FallingBall2.jl
new file mode 100644
index 0000000..535af6d
--- /dev/null
+++ b/examples/FallingBall2.jl
@@ -0,0 +1,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) \ No newline at end of file