physics logo
Physics Practicals

Freefall With Python3 Student Guide

Computational Freefall With Python3 Student Guide Oct. 6, 2023, 1:36 p.m.

Table of contents

    Python is a widely used and versatile programing language, often utilized by physicists and other scientists.

    In the following exercise you will use Python to investigate the motion of a ball in free fall under the influence of gravity. If you are very new to programming, it might be useful to go through the Python intro document at https://computation.physics.utoronto.ca/getting-started-python-3-computational-physics-u-t/ . However, this is not required, and the code for today's practical should be written "from scratch", according to the instructions below.

    • There are questions asked of you throughout this Practical, labeled Question 1, Question 2, etc. ).  Include the answers to these questions in your notebook. 
    • At the end of Activity A, you should save the working code for submission.  You can then rename the code and keep working on adding to it for the subsequent activity.
    • You must reach a consensus with your partners about an answer before moving on to the next part. Feel free to ask the TA for help if a consensus cannot be reached.
    • We assume the motion is always close to Earth’s surface, and therefore we will make the approximation that gravity is a constant g = 9.8 m/s2.
    • All quantities are in SI units; distance in meters (m), time in seconds (s), velocity in m/s, and acceleration in m/s2.
    • Once your codes are working, one of the members of your team must go onto Quercus, select the assignment "Practical 4", and upload the codes for your TA to mark.   

       Activity A       1-D Free-Fall with vi = 0

    In this activity you are going to simulate dropping a ball from a height of 20 m with an initial velocity of 0.

      Question 1: Here is a pretty simple kinematics question: If a small, steel ball is dropped from a height of 20 m, how long does it take for it to hit the ground? Neglect air resistance. 

    On the desktop double-click on "Spyder (Anaconda3)".  Now you can begin typing in code.  Code is a series of statements which tell the computer what to do.  In addition to statements, you may want to comment your code.  Comments are little notes to yourself which the computer knows to ignore.  There are two ways to add comments in Python: one is to put a #-sign in front of the comment, which makes the rest of the line a comment.  The other is to put a line with three double-quotation marks: """, and then the comment on as many lines as you like, and then a second line of three quotation marks to end the comment part.  Notice that the Spyder editor may have put some comments at the beginning of your code automatically.  Feel free to delete these if you would like. 

    The first statement you should add to your code is an import statement, which loads many useful functions.  Please type the following very carefully or cut-and-paste into your code window:

    from numpy import *

    You may as well go ahead and "Save As" the program now so you continue to save it to the same filename while working through this exercise. Call it "freefallexA.py"; you can save it to the Desktop for convenience.

    NOTE: Exercise 1 and Exercise 2 below are meant to be for students who are new to programming.  If either you or your partner are new to programming in Python, please try the next two exercises before moving on.  When you are done the exercises, you can delete the lines of code you wrote during the Exercises.  If both you and your partner are CS students who have written lots of code, feel free to skip these exercises. 


    Exercise 1: How to use the print fuction. 

    You can output values to your python shell window using the print function. If you want to print a character string like hello world, for example, you type:

    print("hello world")

    Save the code, then run it, either by clicking on the green triangle, or by pressing the function key "F5".  In the console window you should see the runfile output, which will say hello world.  If so, you have just written and executed your first working Python code!  Congratulations!

    If you want to define a variable to store a number, and then print the value of that variable, say the variable g, you type the folowing two lines of code, which, when run, will execute one after the other:

    g = 9.8       # define the acceleration due to gravity
    print(g)       # print the value of g

    Remember that everything that comes after a #-sign on a line of Python code is a comment, completely ignored by the computer.  

    Also note that the output just printed 9.8, without any mention of the variable name.  If you want to know what you are printing, you can combine the character strings and the variables.  Try changing the code to:

    g = 9.8     # define the acceleration due to gravity
    print("The acceleration due to gravity is: ", g, "m/s^2")      # a nicer print statement for y'all!

    You can also do math with python.  For example, try changing the code to:

    a = 3.2
    b = 1.25
    c = (a + b)*a
    print("The answer to the math problem is ", c)

    The symbol for multiplication is *, and the symbol for divide is /.  If you want to raise something to an exponent, you use a double-asterisk.  For example, try changing the code to:

    a = 3
    c = a**2
    print("The square of ", a, " is ", c)

    Try different experiments with the print function and make sure you understand what it does before you move on.

    Exercise 2: How to use while loops.

    A while loop statement in Python repeatedly executes a statement as long as a given condition is true.   Try out the following code to make the computer print out the numbers from 1 to 10:

    n = 0
    while n < 10:
        n = n + 1
        print(n)

    In this loop, the condition is "n < 10".  The condition is a "boolean" which means something that can be only either true or false. If the condition is true, for example if n equals 1 or 2 or 9, then whatever is indented below the while statement is performed again and again.  But if the condition is false, for example if n equals 10 or 11 or 100, then the while loop is "broken", and it does not perform the indented commands and instead it goes on to the next part of the code after the while loop.  Try different experiments with the while loop and make sure you understand what it does before you move on.


    If you just completed the above two exercises, you can either delete or comment-out the code you wrote, starting with the hello world statement.  The one thing you will need to keep is the fundamental constant g.  

    Numerical Integration

    When accelertaion is constant, you can write it in terms of change in velocity, and time interval:

    \(a=\frac{\Delta v}{\Delta t}\)
    You can then rearrange this equation for the change in velocity:

    \(\Delta v = a \cdot \Delta t\)

    which can be used to write the velocity at time \(t + \Delta t\)in terms of the velocity at time t:

    \(v(t + \Delta t) = v(t) + a \cdot \Delta t\)

    This equation can be used to update the velocity of something in a “while” loop.   After we update the velocity, we would like to update the position at each time-step. Although technically, the velocity is not a constant in this case, if we take the time interval \(\Delta t\) small enough, the velocity can be approximated as a constant (this of course suggests that the shorter the time tnterval \(\Delta t\), the more accurate our approximation). So we can use the following equation to update the position as long as the time interval is very small:

    \(x(t + \Delta t) = x(t) + v \cdot \Delta t\)

    where v is the updated velocity at each time step. 

    Let's implement a numerical integration in the code.  We are going to create a while loop in time. Start by setting the time-step to a small number:

    #Set the time-step for the numerical integration:
    dt=0.01    # in seconds

    Next you need to set the initial conditions.  The initial condition for time, t, is t = 0.  If we want the ball to start at an initial height of y = 20 m, set y = 20.  And if we want the ball to start falling from rest, set the initial velocity to be v = 0.  Assume v is the y-component of the velocity.  Implement all of this into your code. 

      Question 2: What should your “while” condition be, such that it stops when the ball hits the ground? (The while condition is the boolean that appears just after the word "while", on the same line.) Enter the appropriate while statement into your code with this condition.  Don't forget the colon!  After the while statement, any commands you want to be part of the loop (i.e. repeated over and over again until the ball hits the ground) need to be indented. So make sure to indent the following statements. 

    The first thing you want to do in the indented loop-part is increment the time:

         t = t + dt

     

       Question 3: What commands will you use inside the “while” loop to update the ball’s velocity and position? You need to think about the physics here and use the numerical integration method described above.  After writing the commands into your notebook, type them into your program.  Don’t forget to indent the commands.

    Lastly, within this loop you should print the y-position and the time:

        print("t =", t, "s   y =", y, "m")

    Time to run your code and see if it works!  Don't be discouraged if your code doesn't run properly the first time.  That's normal, and what you need to do is "debug" your code.  A "bug" is a mistake somewhere in your code that you need to fix.  The console will give you hints of where it thinks your bug is.  Keep debugging and re-running your code until it works properly.  You should see a very large number of pairs of (t,y) values as the ball falls.

       Question 4: According to this numerical integration, at what value of time does the ball hit the ground.  How does that compare to your theoretical prediction from Question 1?

       Question 5: Modify your print statement within the loop to also print the velocity of the ball. According to this numerical integration, what is the final y-velocity of the ball when it hits the ground?  Does this make sense according to your kinematics equations? 

    Question 6: Are your velocities becoming increasingly negative at a constant rate? Check by subtracting a few back-to-back pairs of velocities. What should the change in velocity be at each step given your time interval “dt” and acceleration “accel”?

    Question 7: Are your displacements between each step becoming larger with time? Check by subtracting a few pairs of positions.

    Upload your working freefallexA.py code into the "Practical 4" assignment on Quercus.   Make sure both students names are in the comment section near the top.

     

       Activity B       Plotting graphs of your output

    In answering questions Questions 6 and 7 in Activity A, you might have realized that it could become tedious to always check through values to see if your simulation is doing what it is suppose to. Another option is to plot the velocity and position as a function of time and check if these make sense. In this activity we will learn how to make graphs of your output.

    We want to start with the program you just finished in Activity A, but we are going to alter it, so save another copy under a different name (freefallexB.py). Now we can alter this version of the program.

    In order to make plots, the pylab and scipy functions are not enough.  You need to go back up to the top of your code, and, right after the two from statements, add the following statement.  Be sure to type it exactly, or cut-and-paste it from this window:

    import matplotlib.pyplot as plt
    

    So you should now have three statements at the beginning of your program.  Two that start with “from”, and one that starts with "import".  Now you can use various plotting functions, all of which will start with "plt."  For example, plt.plot, plot.show(), etc. 

    Now, within the while loop of your code, remove or comment-out the print statement.  Instead of printing the numerical values, we want to plot them.  the command to send a pair of numbers to a plot looks like this:

        plt.plot(t, y, "ro")

    Notice this is indented, because it is within the while loop.  It sends many many pairs of t and y.  The last text thing "ro" makes red circles on your plot.  Try this code now. 

    You can put a title on the plot with the following command, which should come after the while loop, not indented:

    plt.title("Vertical Position vs Time for Freefall")

    You can also put an axis label on the axes with similar commands plt.xlabel and plt.ylabel.  Please do this.  When you have a nice plot, you should save it, print it, and staple it into your notebook. You should also make a plot of the velocity versus time and include this. 

    Upload your working freefallexB.py code into the "Practical 4" assignment on Quercus.   Make sure both students names are in the comment section near the top.

      Question 8: Answer the question “Was the motion as you expected?” in quantitative detail. For example: is your velocity a linear function? Is your position a quadratic function? Do the signs of your position and velocity make sense?

     

      Question 9: Try larger values of dt.  What is the largest value of dt that you can use and still have a pretty good result for this ball dropping and hitting the ground in 2 seconds?

     

       Activity C       Adding Ad-Hoc Terminal Speed

    We want to start with the program you just finished in Activity B, but we are going to alter it, so save another copy under a different name (freefallexC.py). Now we can alter this version of the program.

    The speed of a real falling object will tend to approach a terminal speed, vterm.  One way of approximating this is to redefine the acceleration as:

    \(a_y=-g \left( 1+\frac{v_y}{|v_{term}|} \right)\)

    Here vy is a negative number, so, as the object falls, vy approaches -vterm, the magnitude of the acceleration goes to zero.  Go into your code, and define a terminal speed, vterm, somewhere before your while loop, perhaps just under where you define g.  Choose something greater than 1 m/s, but less than 20 m/s.  A raindrop, for example, has a terminal speed of 9 m/s.

    Next, inside the loop, change the acceleration to be the equation above.  

    Make plots of both position and velocity vs time for this air resistance case.  Include these plots in your notebook.

    Upload your working freefallexC.py code into the "Practical 4" assignment on Quercus.   Make sure both students names are in the comment section near the top.

      Question 10: What was your value of vterm?   How long did it take the ball to hit the ground, and how did this compare to freefall?   How fast was the ball going when it hit the ground, and how did this compare to freefall?

     

       Activity D       Combining Python and Excel

    Sometimes you need a big Python code to do some tricky numerical integration, but you want to make plots of the output using a spreadsheet, like Excel.  Alter your code above and save it as freefallexD.py.  In this code, instead of printing pairs of (t,y) data to the screen, create a new file, called freefalloutput.csv.  "csv" stands for comma-separated values.  Each line of freefalloutput.csv should have two numbers on it, t and y, separated by a comma. 

    Somewhere before your loop, you should open an output file with an extension ".csv".  The "w" stands for "write".

    file = open('frefallD.csv', 'w')

    Within the loop, add the following commands.  The command str() converts a number to a "string" which is something that can be output to a file.  The first line sends the time, the second line adds a comma, the third line sends the vy vertical velocity, and the last line adds a "return" which is represented by \n for "newline".

        file.write(str(t))
        file.write(',')
        file.write(str(vy))
        file.write('\n')

    Lastly, right at the end of the code, it's good form to close your output file:

    file.close()

    Next, start up Excel, and open the text file freefalloutput.csv, and specify that you are inputting comma-delimited data.  From within Excel, highlight the data and insert an x-y scatter chart. Print it and staple it into your notebook.  

    Upload your working freefallexD.py code into the "Practical 4" assignment on Quercus.   Make sure both students names are in the comment section near the top.

    [Note: This original version of this Module was written by Omar Gamel in September 2014, based on activities written by Sabine Stanley 2010-2014.]

     

    last modified: Oct. 6, 2023, 1:36 p.m.