Logo of Physics Department
Physics 165 - Fall 2004

Introduction to Programming for the Physical Sciences

University of Maryland Logo
.                     

Final Exam:  Dec. 15, 1:30 PM - POWL

Practice Question and Solution


  Remember to go on-line and fill out COURSE EVALUATION


fear the turtle imagefear the turtle image
Course Information
Syllabus Assignments
Mac Users
Submitting Programming Problems
 Synopsis of Material Covered
Solutions to Programming assignments
Programming Evaluation Criteria
Programming Project
 Exams
 Lab Activities
Final Exam Date

Course Information

The course will cover basic programming skills using examples from the physical sciences.  The course prerequisite is one semester of a calculus-based physics course such as Phys 141, 161 or 171, or credit on the physics AP exam.  The language used is Python, which is an interpreted, object-oriented language with both scripting and systems level capabilities.  The course will use Python to provide instruction in the standard programming techniques used in upper-level languages.  The course will include a strong component of visualization and graphing using the  tools available through the VPython* implementation.

While this course satisfies the lower-level requirement in Computer Sciences for Physical Sciences majors and Math majors, it is not a substitute for CMSC 106 (which uses the C language), and thus does not satisfy the prerequisite for upper-level CMSC courses.  This course will provide a useful preparation for Phys 474 (Computational Physics) or Astr 415 (Computational Astrophysics), although Python is not the language used in either of those courses. 

*The Visual library is Copyright (c) 2000 by David Scherer.

decoration

Syllabus

back to top
Physics 165 - Introduction to Programming for the Physical Sciences

Instructor:  Professor E. Williams  (http://www.physics.umd.edu/spg/)
Room 2332 Physics,
Phone 301-405-6156
course web page:   http://www.physics.umd.edu/courses/Phys165/williams2004/
e-mail:  edw@physics.umd.edu (you must include  "Phys 165 Fall 04"  in subject line)
for help with class:  phone, e-mail or see me after class to make an appointment

Class Location:
M W F  3:00 PM, Room 1402 Physics
Approximately one day per week as announced, class will be moved to Room 3115 Physics (POWL)

Course Software:  Python 2.3 and VPython*

The software is installed and available for use in the Physics Open Workstation Laboratory (POWL), room 3115 Physics Bldg.  I strongly recommend that you install a copy of the software on your personal computer, so that you can work and  maintain your own files conveniently.  The course software is available as freeware at:  http://www.vpython.org/download.html      If you follow the download instructions carefully you should have no problem getting VPython up and running - just read all the instructions before you start. 

*The Visual library is Copyright (c) 2000 by David Scherer.

Textbook:     Python Programming:  An Introduction to Computer Science, J. Zelle, Franklin, Beedle and Assoc. 2004

Required Downloads:  (additional required reference material will be indicated as needed in the course)

VPython Reference Manual, R. Chabay, D. Scherer, and B. Sherwood
    http://www.vpython.org/webdoc/index.html

References:
Python:  Visual Quickstart Guide, C. Fehily, Peachpit Press, 2002
Learning Python, M. Lutz and D. Ascher, O’Reilly, 1999
An Introduction to Computer Simulation Methods, H. Gould and J. Tobochnik, Addison-Wesley, 1996

For more  information on Python programming and scientific computation, see the outstanding compilation of references made by Prof. Einstein at:  http://www.physics.umd.edu/courses/Phys165/einstein/refs.html

Material:  We will be covering material in Ch. 1-11 of the text, with a heavy emphasis on Ch. 6-11.  The class will emphasize science applications with examples from orbits, vibrations and stochastic processes, which will be reviewed or introduced in class lectures.   We will also cover simple numerical solutions of differential equations using the Euler method. 

Evaluations:
1. Homework, 1 set per week, due Friday at or before the beginning of class.
2. Programming Project:  Due Monday Dec. 6, class presentations of projects Dec. 6-10.
3. Practical Exams:   October 8, Nov. 19
4. Final Exam:  Wednesday, Dec. 15, 1:30-3:30 PM
Grading
Homework: 30%
Programming Project:  30%
Exams 40%
Academic Honesty
Working together on assignments is encouraged.  However, each student is expected to do the assigned problems and write the assigned programs independently, and hand in his or her own work for grading.  For any questions about academic honesty, see University policies at:
http://www.testudo.umd.edu/soc/dishonesty.html
back to top
 Course Logistics:

We will have class in the Workstation Lab (room 3115 Physics) most Fridays, and and on other dates to be announced as well.   If you arrive in room 1402 and find no class there, go to 3115.   Make sure you always bring PC-formatted floppy disks to the Lab (both for classes there and when you are working on assignments there) so that you can save your work.  There are a large number of demonstration programs that are automatically included with the VPython download.  These are on the server in the Workstation Lab.  You are welcome to copy these to study and to edit them to create new programs.

The programming project and most homework assignments will require creation of computer programs.  You will submit these by e-mail.  Send them to me at edw@umd.edu, and you MUST include "Phys 165 Fall 04"  in the subject line or your e-mail will not end up where it needs to be for me to look at it.  If I can’t open the files you send  on the first try using Python, the grade for the assignment will be zero.  So make sure you've mastered e-mailing files: you should test this in advance by exchanging files with a friend.   I will NOT look at any files unless:
      1)   The subject line on the e-mail is "Phys 165 Fall 04"
      2)   The listing of any attached program(s) is pasted into the e-mail body as text.
      3)   The title of the file is "<yourname><A#><P#>.py  
             For example "williamsA2P3.py" would be problem three from assignment two, handed in by Williams.

Remember, it is your responsibility to make sure the file reaches me in a form that works!  

If you are using Yahoo as your e-mail server, there is a problem with attached files (they are not coming through as attachments).   Two things that will correct this are:  1)  zip the files before sending as attachments, 2)  use a different e-mail server, e.g. your UMD account.   Please make sure your files reach me in useable form by using one of these correction methods.

Successful programming requires logical thought and a lot of organization.  You should  organize the files you create on your disks with self-evident names in a logical structure of folders.  Your python files can also be printed (for storage in your ring binder and easy reading) by copying the text from the IDLE window and pasting it into the editing/word processing program of your choice (e.g. bbEdit, Word…).

decoration

back to top
Solution Sets

Programming solutions to the assignments will be posted on the Delphi network, which you can access from the POWL lab.  The solutions (and occasional other miscellaneous information) will be on the drive "Course on Delphi\Groups(P:), in the folder P165.

decoration

back to top
Assignments

Physics 165, Fall 2001

Assignment # 11
    Classes, class methods, operator overloading, GUI
Reading:       Zelle, Chapter 10, sections 1-4, and 7
See also: http://www.ibiblio.org/obp/thinkCSpy/chap14.htm (section 4.8, overloading)
                Python reference manual:  section 3.3.7 (emulating numeric types)

Assignment:  Due Friday, December 10

Problem 1:   Create a statistics program that reads in two lists from a pickled file that was created using the code:

file=open('name.dat','w')
pickle.dump((list1,list2), file)
file.close()

and calculates the average and standard deviation (a1 and s1, and a2 and s2) for the numbers in each list.  Then have the program calculate  z = a1**5.2 and the standard deviation of z, and w = x/y and the standard deviation of w.  Your program should define and use two classes: 

1)  The first class will calculate the average and standard deviation of the lists of numbers.  You can modify the class Statdat (see below) to include two methods, one to calculate the average and the other to calculate the standard deviation of the numbers in a list.  (see A4P2 for ave and std calculations)

2)  The second class should have attributes val (value) and std (standard deviation), and will perform error propagation on operations “raise to a power” and “divide”.  Use operator overloading to return a new member of the class with the correct value and standard deviation for each operation.
ation for each operation.

class Statdat:
    def __init__(self, data=[]):
        self.data=data
        self.avg=0.
        self.rms=0.
        self.std=0.
        self.stdbar=0.
    def __pow__(self,other):  #Note this operator overload is not used in this problem set
                      # and it can be omitted in the program you write, although
                     # a similar operator will be needed in the second class
        list=[]
        for i in range(len(self.data)):
            list.append(self.data[i]**other)
        list=Statdat(list)
        list.stdbar=(other*self.avg**(other-1))*self.std
        return list

Problem 2:   Create an interactive game that asks the user for a time interval in seconds, and then allows the user to click two buttons, one to start and one to stop a timer.  The game will then report the user’s time interval between the clicks and allow the user to choose whether or not to repeat the game. 
    Use the POWL exercise instructions from Nov. 12 and 17 to help develop the program. 

back to top

Assignment # 10    Classes and energy in Euler calculation
Reading:       Zelle, Chapter 10, sections 1-4
See also:  http://www.ibiblio.org/obp/thinkCSpy/chap14.htm (classes and methods)

Assignment:  Due Friday, Nov. 12

Problem 1:  
A good way of checking the accuracy of a numerical calculation is to calculate the energy of the system and make sure it is conserved.  Modify the program springs.py, used in the class activity on Nov. 5, to do this, using class attributes to carry the energy information following the instructions in steps a)-c). 
a)  Add two attributes to the elements of the list atoms,  atoms[i].ke and atoms[i].pe  (for kinetic energy and potential energy), and initialize them to zero in the same way that the momentum attribute atoms[i].p is initialized. 
b) 
When atom ith is displaced, this will change the potential energy of atoms ith-1, ith and ith+1.  Update the PE for each of these atoms using the PE equation for a spring:
     atoms[i].pe = 0.5*ks*(atoms[i].x-atoms[i-1].x-d)**2 + 0.5*ks*(atoms[i+1].x-atoms[i].x-d)**2
where d is the equilibrium spacing.  Find the total system energy at this starting point by summing the potential energies of these three atoms and print the value.
c)  In the Euler loop, update the kinetic energy and potential energy of each atom at the same time that the force is updated.  Every 100th time step, find the total system energy and print its value as well as the percent change from the original total system energy. 

**20 extra points
for this problem.  Include the program modification (and output) to estimate the speed of sound from the POWL activity of Nov. 5. 

Problem 2: 
Modify the class definition in the projectile program on p. 308-309 to make it a 3-dimensional calculation, with z the vertical direction, x and y horizontal, and phi the  horizontal angle with respect to +x at which the projectile is fired.  Add a small constant horizontal acceleration of 0.05m/s^2 in the positive y direction to mimic the effect of wind.

Modify the getInputs function and the main program to set up an iterative process to hit a target (define hit as within 10 m) at x = y = 20km and z = 100m.   You will need to input the initial settings (theta, phi, v, h, t), and output the final position (x,y,z) and then query the user for a new set of inputs, etc., until the user decides the projectile has hit the target.  Report (in a comment line) the input values you found to hit the given target position.

**typical muzzle velocities should be around 1000 m/s. 

REDO problem: 
Due no later than Nov. 22.   To earn up to 80% of the points missed on problem 1 of assignment 8, redo the program and resubmit. 

back to top
Assignment # 9    nested loops and lists, vectors

Reading:      
Vpython reference manual:  the vector object
If you want to know more about the difference between Python nested lists and the array function that supports the vector object in Vpython, see: http://www.pfdubois.com/numpy/html2/numpy.html

Assignment:  Due Friday, Nov. 5

Problem 1:   Write a program to calculate the multi-body forces in a system of three objects interacting via the gravitational force. Your program should use one meaningful function.  It should use vectors for the positions and forces.   The three objects will have the parameters:
    object 1:   mass = 10.0 kg,   position =   0.0m x + 0.0m y + 0.0m z.
    object 2:   mass = 25.0 kg,   position =  -1.0m x + 5.0m y + 0.0m z.
    object 3:   mass = 100.0 kg,   position = 1.0m x + 5.0m y + 0.0m z.
The program should provide two outputs:
a)  A neatly formatted matrix of the magnitude of the nine force components (f11, f12,  etc.)
b)  A neatly formatted list of the net force vector on each object.

Problem 2:
This is a follow-up to the POWL exercise of Oct. 22 on modifying a complex program.  The exercise will be to change the code in the program gas.py so that the atom colors, instead of being assigned randomly to fixed values, are assigned to span a color range based on the momentum of each atom. 
Open the program gas.py, add a comment statement at the beginning indicating its origin and save it as <yourname>P9A2.py.  You will need to choose a spectrum of colors to indicate coldest (lowest momentum) to hottest (highest momentum).  You will also need to define a mathematical relationship between the momentum and the indices of the color code. 

Look through the code, and identify the for loop (for i in range(Natoms):)  where the colors of the atoms are defined, as well as their original momenta (pavg).  Move the color assignment statement after the pavg calculation, and define the colors of all the atoms to the same value that you want to correspond to pavg. 
Now look through the program and find the for loop that governs collisions (this is the only place that atoms change momenta).  The momenta of the two atoms i and j after the collision is indicated by vectors p(i) and p(j).  Add lines of code to find the magnitude of the momentum for those two atoms*.  Then use the new momentum to update their colors.

*Atoms is a list of vpython spheres (see vpython manual).  Thus each element of the list, Atoms[i] has attributes such as pos and color that can be addressed and changed via:
Atoms[i].pos = (x,y,z),         Atoms[i].color = (1,.5,.25). 

Problem 3: 
Write a technical description of your plan for your programming project.  Provide the following information:
a)  Title or topic
b)  Statement of the question to be answered.  The question must indicate independent and dependent variables.  (An example would be:  my program will show how the mean squared displacement of a random walker changes when there are more and more blocked sites.  Here the independent variable is the number of blocked sites, and the dependent variable is the mean squared displacment).
c)  Describe the computing approach that will be used in your program (An example would be, I will define a starting geometry for <list of objects in your problem> and calculate the forces (describe which forces are included) and then use the Euler equations to predict the motion). 
d)  List the input parameters and constants that will be used, and the output parameters that will result.  Each item should have a brief definition so it’s clear how the parameters are related to your computing approach. 
back to top
Assignment  8   Files,  color

Reading:          Rearead Zelle  4.6
           
             Python tutorial:  Section 7.2.2 (pickling)

Interesting parallel information:
Graphics files:     http://www.ideabook.com/007_vbit/vbit.htm
Color:      http://www.cox-internet.com/ast305/color.html
                http://www.cs.rit.edu/%7Encs/color/
                http://www.cs.rit.edu/%7Encs/color/t_convert.html

Programming Assignment:  Due Friday, Oct. 29

Problem 1: 
Write a program to read from the data file "table.doc" ( on course server) and create a numeric list (or two lists) representing the saturated vapor density (in g/cm^3) vs. the temperature (in degrees C).  You will need to look at the original table on the web site http://hyperphysics.phy-astr.gsu.edu/hbase/hframe.html  (use the index and choose vapor pressure) to see how the text file represents the tabulated values.  I will test your program on the original "table.doc," so don’t edit the file to make the input easier!

Problem 2: 
Write a program that creates a list named “mixed” of 10 mixed-type objects (strings, floats, integers, other lists).  Have the program “pickle” the string to an output file.  Close the file, reopen, and load the file contents to a new list named “pickled”.  Write a loop to compare the two lists and report on whether or not they are identical. 

Problem 3:
This is a follow-up to the POWL exercise of Oct. 13 on RGB color definition. Start with the following short code, which generates a spiral that evolves from magenta (1 0 1) at time 0 to cyan (0 1 1) at the end, time 10.  You can use the program “colorsliders.py” to see how the color code (a b c) relates to color choices. 

from visual import *
helixcurve = curve(radius=0.05)
for t in arange(0,10,0.01):
    rate(100)
    helixcurve.append(pos=(cos(3*t),sin(3*t),t), color=(1-t/10., t/10., 1))

 Modify the code so that it also draws:
i.  
a second spiral, offset in position from the first, that evolves from yellow to blue.
ii. 
a third spiral,  offset in position from the first two, that is white in the first quadrant (x>=0,y>=0), blue in the second quadrant (x<0,y>=0), green in the third quadrant (x<0,y<0), and red in the fourth quadrant (x>=0,y<0).
Your program should create one graphical output with three spirals each with a different color scheme as specified. 


back to top

Assignment  7 
Histograms, files, exam problem
Reread:    Zelle Ch. 7 section 5 (note max function) and Ch 11 sections 2.1.and 2.2
Read:        Zelle Ch. 4 Sections 4.4.1, 4.6

 For additional description and examples see: 
http://www.ibiblio.org/obp/thinkCSpy/chap09.htm  (histograms)
http://www.ibiblio.org/obp/thinkCSpy/chap11.htm  (files and exceptions)
 See also:     Python Library Reference     section 2.1  (built in functions)
                                                                  section 2.3.8 (file objects)
                    Python Tutorial                     Section  7.2 (files)
                    http://www.asciitable.com/    ASCII code

Problem Set:  Due Friday, Oct. 22

1:  Write a function to create a list of the histogram values given a list of numbers.  Your function should input only the list and the number of “bins” desired – your function should define the bin size and range from the properties of the list.  Your function should output a list of the histogram values , the  minimum value of the range, the bin width,  and the number of bins.  Create a program that prompts the user for the number of bins, generates a list of 1000 random numbers and prints out a neat list of the bin range and number in that range.
NOTE:  15 extra points if you create a histogram function that involves only one loop, rather than the two loop structure discussed inclass. 

2:  Write a program that generates three lists of length 100, and writes the three lists to an output file as three columns, in a format that can be pasted directly into a spreadsheet.  The first list should be the numbers from 0 to 99.  The 2d and 3d lists should each be a function (your choice) of the corresponding numbers in the first list.  The name of the output file should be <yourlastname>out.dat  (e.g. my file will be williamsout.dat).  You should test your output file by opening it with a text editor and copying the data into a spreadsheet such as Excel in exactly one cut/paste operation.

3:  Rework/extension of exam.  Do only one of a or b.
a)   If you earned 85 or lower on the exam, fix all problems so that it runs perfectly. 
b)  If you earned higher than 85 on the exam, do the following problem: 
Correct any problems in your program, and modify the end of the program (where the distance of closest approach is found) to improve the estimate of the value of the closest position using linear interpolation. 

back to top
Assignment 6
Read:
         
Zelle, Chapter 6
For other examples of the use of functions, see also: 
  http://www.honors.montana.edu/~jjc/easytut/easytut/node9.html
and/or
  http://www.ibiblio.org/obp/thinkCSpy/chap05.htm
                  (sections 5.1 through 5.3)

Problem Set:  Due Friday Oct. 15

1:  Write a function to find the roots of the quadratic equation a*x**2 + b*x + c = 0, and return the two roots to the main program.  Write a test program that prompts the user to provide values for a,b and c, and uses your function to find the roots, and prints the results.   (Be careful - if the person entering the values of the constants chooses integers you may get strange results.  So make sure your calculation treats the values as floating point numbers.  Also – make sure your program can handle an imaginary root.)

2.  Functions can call other functions, and use of default variables:

Write a program that includes a function “accel” that can call an arbitrary force function and use it to calculate the acceleration of an object given its mass.  Write two force functions “fgrav”, and “fspring” that can calculate the force on an object given the appropriate parameters.  The two force functions should calculate:

The gravitational force (fgrav)   F = -GmM/r**2
The spring force (fspring)         F =  -kx.

Have your program prompt the user to input masses and distance for gravitational force; then input mass, spring constant and displacement for spring force.  Then use the function “accel” to calculate each acceleration (in the case of gravity assume one of the masses is unmoving and calculate the acceleration of the other) and print out the results. 


Problem Set:  Due Friday Oct. 15
          to be assigned
back to top
Assignment 5
Read: 
Zelle  Chapter 9, sections 1 and 2
Zelle Chapter 7, sections 1-3 and 5-6 (we will do exceptions later)
Python tutorial sections 4.1 through 4.4

Problem Set:
   Due Friday Oct. 1

1.  Zelle, Ch. 9 problem 10 (p. 292)  

2. Turn in your solution to the hole in the floor problem started in the computer lab.  (see Sept. 24 document).

3.   Try the three segments of code below (available in course folder as prime.py in case you don't want to retype them) and make sure you understand exactly what each one is doing.  Then:
a)   choose one of the codes and modify it to allow screen input of the maximum number to be tested, and to list all the factorizations for each number (e.g. 2*4 and 4*2 for 8),.
b) modify your code to  list all the unique factorizations for each number (e.g. 2*4 only for 8, but 3*4 and 2*6 for 12).

Test your programs to make sure they work for larger ranges.  Make sure you identify which code you started with for each of your programs.
   

#VERSION 1
for n in range(2,13):
    for x in range (2,n):
        if n%x==0:
            print n, "equals", x, "*",  n/x
        else:
            print n, 'is a prime number'
print "the program is done"

#VERSION 2
print "\n second trial program \n"
for n in range(2,13):
    for x in range (2,n):
        if n%x==0:
            print n, "equals", x, "*",  n/x
            break
    else:
            print n, 'is a prime number'
print "the program is done"

#VERSION #3
print "\n third trial program \n"
for n in range(2,13):
    for x in range (2,n):
        if n%x==0:
            print n, "equals", x, "*",  n/x
            break
    print n, 'is a prime number'
print "the program is done"

Follow the systematic steps outlined in Zelle (see p. 45) for developing a program.  Remember to include documentation, and to create a clear and professional looking output. 

back to top

Assignment 4

Read:   
 
   Python Tutorial, sections 3, 4.3
    Python Library Reference, section 5.8
    Zelle
        Chapter 4, sections 1-3
        Chapter 9, sections 1-2
        Chapter11, sections 1-2

Problem Set:
Due Friday, Sept. 24

1. 
Zelle, Ch. 4 problem 5 (p. 119)  

2. 
Modify the program on p. 338 of Zelle to store the input numbers in a list, to sort the list in numerical order (from smallest to largest) and to calculate both the mean and the standard deviation of the numbers.  Your program should create an output with the ordered list of numbers, the mean and the standard deviation.

Follow the systematic steps outlined in Zelle (see p. 45) for developing a program.  Remember to include documentation, and to create a clear and professional looking output. 

Submit your programs by email as per web page instructions.   

back to top

Assignment 3

Read:         VPython Documentation:  Python Tutorial, section 3.2 and 4.2
Chapter 3 of Zelle, and Section 4.5.2 of Zelle

Problem Set 3:
Due: Friday Sept. 17

1.  
Write a program to calculate the speed and position vs. time of an object falling from geosynchronous orbit (circular orbit of period one day) straight down to the surface of the earth.  Use Euler’s method to solve the equation of motion numerically.  Have the program print out the time, position and velocity at the starting point, when the object is 1/4, 1/2 and 3/4 of the way down and when the object hits the earth.  Neglect frictional effects due to air.    Use the techniques of section 4.5.2 of Zelle to make sure your output is neatly aligned and professional looking.

2. 
Problem 15 in Zelle Ch. 3 (p. 74).

For programming exercises:  remember documentation, units on numbers and professional looking screen input-output.  Follow the systematic steps outlined in Zelle for developing a program.

Submit your programs by email as per web page instructions. 

If you are using Yahoo
as your e-mail server, there is a problem with attached files (they are not coming through as attachments).   Two things that will correct this are:  1)  zip the files before sending as attachments, 2)  use a different e-mail server, e.g. your UMD account.   Please make sure your files reach me in useable form by using one of these correction methods.

back to top

Assignment 2

Read: 
VPython Documentation:  Introduction and Spheres
            Chapter 2 of Zelle

Print the documentation on Mathematical Modules from the Global Module Reference.  Install it in your binder of Python/Vpython documentation. 

Problem Set Due
: Friday Sept. 10

1. Write a program to read in TWO values of radius from the screen, calculate the area and circumference of a circle for each radius, and print out the answers.

2.  Problems 1 and 3 in Zelle (p. 49) – submit one program that includes both problems.

For programming exercises:  remember documentation, units on numbers and professional looking screen input-output.  Follow the systematic steps outlined in Zelle for developing a program.

Submit your programs by email as per instructions above.   

back to top

Assignment 1

Read Chapter 1 of Zelle, working through the examples on p. 9-17
Download, print and insert in a well-organized notebook the VPython Reference Manual

Problem Set Due:  Friday, September 3

You will hand this problem set in on paper, do not send in anything by e-mail

Zelle, Ch. 1, (p. 22-23)  programming exercises #1 and # 3

decoration

back to top
POWL Activities

POWL activities, Wednesday Nov. 17, 2004

This activity will serve as the basis for one problem on Assignment 11, so be sure to save your work. 

You will use the time module from Python as well as the buttons controller from Vpython to set up an interactive timing game. 

Look at section 6.10 in the Library reference.  Open the python shell and type “from time import * “ to load the time module.

Try the commands:  clock(),  time(), localtime() {try localtime(clock()) and localtime(time()} and check what they mean with the Library reference.

We will begin to create a timer program based on the sample program code (see Nov. 12 POWL activity) in the Vpython reference manual chapter “Controls: buttons, sliders, toggles, and menus “ 

Modify the code to import the time module, and to add a second button and a second function definition to go with it.  Rename the first button “start the timer” and name the new button “stop the timer”  Define a global parameter t1 in button 1’s function and have the function call time, and a global parameter t2 in button 2’s function which also calls time. 

Set t2=0.0 before the while loop, have the while loop run while t2==0.  After the while loop terminates, have the program print out t2-t1.  Start the timer by clicking button 1 and stop the timer while clicking button 2.  See how well you can control the time interval. 

For problem set 11, you will turn this into an interactive program that asks you to input a time and then tells you how well you have done, and gives you the option to try again. 

back to top
POWL activities, Friday Nov. 12, 2004

Graphical User Interface (GUI) through Vpython –
incorporating screen interactions via the mouse into an active program.

For information on other GUI’s useable with Python see:

http://www.awaretek.com/toolkits.html

Activity:

Start the Python IDLE.  Begin a program with your standard (name, date etc) commentlines, and then type in the command “from visual import *”

Open the Vpython documentation (reference manual) and scroll down to the heading
    “Windows, Mouse, and Keyboard Interactions”
Choose Mouse Interactions.  Read the first three paragraphs and then go back to the first paragraph and click on the link “Click example”.  Type the first block of code into your edit window and run the program.  Try to place a red sphere as close as possible to the position (2.0, 2.0, 0).  Show me your result.   Save your program. 

Go back to the Python documentation and select the “Drag example” link.  Use triple quotes to suspend the original code in your edit box, and type in the block of code dragging  into your edit box.  Run the program and try dragging the sphere.  Now modify the program to print the location of the sphere (see the click example) after each drag.  Show me your result and save your program.

No go two chapter forward in the Vpython reference manual to the chapter “Controls: buttons, sliders, toggles, and menus “  Quote out your previous code in your program, and type in the block of code for the example.  Run the code and try clicking the button.  Modify the code to create another button with action of your choice.  Show me your result and save your program.

If time permits, run the demo program controlstest.py and try some modifications.  

back to top

POWL activities, Friday Nov. 5, 2004

Multi-body systems, speed of sound in a solid

Run the demo program sound.py (in the course folder on the server) and test the function of each of the four screens in the program. 

Now open the file spring.py and add a comment line indicating that you are modifying it. 

The wave of displacements that travel through the chain of atoms is a sound wave – but one that travels much more quickly than sound in air.  By measuring the time difference between the initiation of a pulse at one atom and the first time a distant atom first responds to the displacement wave, we can determine the speed of sound in the solid.  The spring constant, mass and inter-atom spacing in this example are physically meaningful values for Aluminum. 

You will modify the program to estimate the speed of sound, and test the performance of your modified program for many different choices of the “clicked” atom. 

1.  To begin:  look down the program to the while loop where the mouse click is registered.  Notice that the clicked atom is assigned the index ith. 

2.  Given that the wave is initiated at atom # ith, decide on the value of the atom # at which you will detect the arrival of the sound wave.  Add some code before the while loop where the Euler calculation is done to define this value. 

3.  The position of each atom at the start of the calculation is atoms[i].x = i*d.  Look in the Euler loop and find the line of code where the atomic positions are updated. 

4.  The initial displacement of the first atom is 0.3*d.  What criterion will you use to decide when the sound wave has reached your test atom?  (remember testing for exact equality is dangerous in numerical solutions).  Add a decision statement with this test in an appropriate place in the Euler loop.

5.  What equation will you use to calculate the sound speed?  Add this calculation to your code.  Add a print statement to output the speed of sound.  Check the original units on the parameters to get the units on the speed. 

6.  How will you make sure that the sound speed calculation only happens at the first displacement of your test atom?  Add this control to your code.

7.  Run your program several times for different positions of the first “clicked” atom, and record the values of the sound speed you calculate.  Show me your results and one run of your program. 

8.  Save your program, it will be used in the next assignment. 

back to top
POWL activities, Friday Oct. 29, 2004

Nested Loops and Geometric Structure

Run the program crystal.py.  This program shows a model crystal of 27 “atoms” connected by springs.  A small amount of kinetic energy is randomly assigned to each atom as a starting condition to simulate thermal motion.

We will look at the use of indices and nested loops in such a structure.  Find the program 3dcrystal.py in the course folder.  Open and run it.  I have just extracted the code from crystal.py that is used to create and display the atomic positions.

Notice that the horizontal layers have different colors (top layer, bottom layer, middle layer).  Look at the structure of the THREE nexted loops and understand how this color assignment was generated.

Now “un-comment” the lines of code at the end of the program to see how the array has been set up.  The out list of “atoms” runs from 0 to 26 with attributes including position, color and indices for each “atom.

Write a set of nested loops (one each for x, y and z coordinate) outside of the function definitions that allows you to have three vertical planes of different color – the left layer, middle layer and the right layer. 

Code for 3dcrystal.py:

#Modified segment from crystal.py program
#3dcrystal.py
#Ellen Williams, Oct. 28, 2004


from visual import *
from random import random

N = 3
Ntotal = N*N*N
objects = []

def getn(N, nx, ny, nz): # find nth atom given nx, ny, nz
    return (ny)*(N**2)+(nx)*N+(nz)

   
def crystal(N=3, delta=1.0, R=None, sradius=None):
    atoms =[]
    R = 0.2*delta
    sradius = R/5.
   
    xmin = -(N-1.0)/2.
    ymin = xmin
    zmin = xmin
 
    natom = 0
    for ny in range(N):
   
        y = ymin+ny*delta
        n1 = float(ny)/(N)
        c = (n1,.8, 1.-n1)
       
        for nx in range(N):
            x = xmin+nx*delta
           
            for nz in range(N):
                z = zmin+nz*delta
                atoms.append(sphere(pos=(x,y,z), radius=R, color=c))
                atoms[-1].indices = (nx,ny,nz)
                natom = natom+1
    #print natom
    #for a in atoms: print a.indices
    #for a in atoms: print a.pos
               
    return atoms

objects = crystal()
print len(objects)


#identify atoms # zero and 27 on the display


#index =getn(N,0,0,0)
#print "the (0,0,0) corner atom is atom #", index
#print "I will color it yellow "
#objects[index].color=(1,1,0)
#print "Its xyz coordinates are ", objects[index].pos, '\n'

#index=getn(N,2,2,2)
#print "the (1,1,1) corner atom is atom #", index
#print "I will color it red "
#objects[index].color=(1,0,0)
#print "Its xyz coordinates are ", objects[index].pos, '\n'
   
back to top
POWL activities, Friday Oct. 22, 2004

Choose one of the following two class activities:

1)  Activity 1   Functions
If you received a large asterisk (*) on your grading sheet for PS 6 you should do activity one.  Or, if you just feel that additional practice with working on function definition and use would be helpful to you, please do this activity.

Go to the web page: http://www.ibiblio.org/obp/thinkCSpy/chap05.htm

Read through each of lessons 5.1 and 5.2 and then take the assigned problem at the end of the section, and go back to the beginning following the text step-by-step to complete the problem.  

2)  Activity 2 Modifying a complex program

Open the program gas.py, add a comment statement at the beginning indicating its origin and save it as gasmod.py.

The exercise will be to change the code so that the atom colors, instead of being assigned randomly to a fixed value, are assigned to span a color range based on the momentum of each atom. 

Use the color sliders program to identify a color sequence that you’d like to use.  

Look through the code, and identify the for loop (for in in range(Natoms): where the colors of the atoms are defined, as well as their original momenta (pavg).  Move the color assignment statement after the pavg calculation, and define the colors of all the atoms based on pavg. 

Now look through the program to the for loop that governs collisions (this is the only place that atoms change momentum).  The changed momenta of the two atoms i and j is indicated by vectors p(i) and p(j).  Add lines of code to find the total momentum for those two atoms.  Then use the new momentum to update their colors. 

Hints: 

The momenta p[i] and p[j] are python vector quantities. (see class notes from Sept. 8-15).   That means they have three components which can be addressed individually as p[i][0], p[i][2] and p[i][2], etc.  There is also a built-in python function to find the magnitude of a vector:   mag(p[i]).

Atoms is a list of vpython spheres (see vpython manual).  Thus each element of the list, Atoms[i] has attributes such as pos and color that can be addressed and changed via:
Atoms[i].pos = (x,y,z),         Atoms[i].color = (1,.5,.25). 

back to top
POWL Activities – Oct. 13

1.  Control of color

Open the Vpython file colorsliders and experiment with moving the sliders around to generate different colors.  The three integers that are displayed are the rgb code that generates color – as in the vpython command “color = (a,b,c).

The integers that define color can be controlled by program variables:

Type in one of the following short codes, which generate a spiral that evolves from magenta (1 0 1) at time 0 to cyan (0 1 1) at the end, time 10. Be sure to rotate your field of view out of the x-y plane (drag with your mouse while right-clicking) to get a 3D view.

from visual import *
helixcurve = curve(radius=0.05)
for t in arange(0,10,0.01):

    rate(100)
    helixcurve.append(pos=(cos(3*t),sin(3*t),t), color=(1-t/10., t/10., 1))

Note that the code could also have been written

from visual import *
helixcurve = curve(radius=0.05)
for t in arange(0,10,0.01):

    rate(100)
    helixpointcolor=(1-t/10., t/10., 1)
    helixpos=(cos(3*t),sin(3*t),t)
    helixcurve.append(pos=helixpos, color=helixpointcolor)

Modify the code so that the spiral evolves from yellow to blue: you need only change the argument of color=( ), or the right side of helixpointcolor=( ) in the alternative code.

2.  Graphical output using Vpython

Look at the  Vpython Visual Reference section on Graph Plotting. 

Run the Vpython program graphtest.py.  Now add the command “rate(10)” after the “for” command, and run the program again.

Note the for loop command “arange”.  This is a special Vpython operation that allows the counter to incremented by non-integer amounts.  Change the command to arange(-30,70,0.2) and run the program again.  Reset arange.

Modify the program by adding “xmax=70, xmin=-30,” to the list of definitions in gdisplay(…..).  Change the arrange command to run from.

Run the program again with different values of xmin and xmax while keeping the arange limits the same. 

3.  Histogram plotting using Vpython

Look at the information about histogram plotting in the documentation, and try the following code:

from visual.graph import *

agelist1 = [5, 37, 12, 21, 8, 63, 52, 75, 7]
ages = ghistogram(bins=arange(0, 81, 20), color=color.red, xmax=100)
ages.plot(data=agelist1) # plot the age distribution

Run the program to create a histogram. 

Modify the program to create a list of random numbers and plot the histogram of 1000 random numbers. 


back to top
POWL - Class Activity, Sept. 24, 2004

* before you get started – make sure you make copies of the two programs holeinthefloor.py and prime.py from the course folder.  You will need both for this week’s assignment.  

1) Another programming tool

Open the python shell and try the % command.  When used in mathematical expressions, this is the “remainder” function.  Try the following:

>>> 3 % 4
>>> 4 % 3
>>> 4.% 3.
>>> 3 % 3
>>> 3 % 6
>>> 6 % 3

2)  More control statements (if, elif, else): 

Open Python help and look at the python tutorial, sections 4.1 and 4.4.   Type the codes there into the python editor and run the programs with different inputs to make sure you follow the program decision structure.  (see also Zelle, p. 212)

3)  Working through complex controls:  Use the Python IDLE browser to go to the P165 folder on the disk Course on ‘Delphi\Groupsnew’.  Open the program holeinthefloor.py and run it (let it go for several passes of the ball left to right and back until it hits the hole).  Try changing the initial x-component of the velocity and run it again.

Now take out a sheet of paper, and make a flowchart of the control sequence in the program.  Specifically pay attention to how the radius of the ball and the height (which means thickness) of the floor – add sketches to your flow chart to show explicitly the physical meaning of the decision points for turning around.    Show me your flow chart.

After the flow chart is done, evaluate and add to your flowchart the modifications that will be needed to:
a) get the ball to fall through the hole in the floor and keep falling until it disappears off the screen.
b) get the ball to fall through the hole in the floor and when it disappears off the bottom  of the screen, reappear at the top and continue to move properly.

Begin testing and implementing your modified program.  This final solution will be handed in as part of next week’s assignment. 

back to top

POWL - Class Activity, Sept. 17, 2004 

1)  Order of operations in computer equations: 

Generally, algebraic computer operations are executed with the same ordering that is used in standard algebra:  exponentiation is done first, multiplication and division next, and then addition/subtraction.  Try the following examples in the Python shell to see what this means for your programs:

x=8.
y=x**1/3
y
y=x**(1/3)
y
y=x**(1./3.)
y
y=5.*x**2
Y
y=5.*x**2/3.+2.
y
y=5*x**2/(3.+2.)
y

2)  Introduction to Lists:  Go to Python Help and open the Python Tutorial.  In the Python shell, go through the introductory exercises in section 3.1.4, 5.1.1, 5.1.2.  
Optional:
If you’d like to see some advanced list manipulations, work through the “vec” exercises in section 5.1.4.  Python also includes (through the numeric module that is included in visual) some advanced array processing capabilities.  If you are interested in this, see the Numeric documentation at: http://www.pfdubois.com/numpy/ - you have to scroll down a bit to get to the documentation links.  Again – note you do not need to download this.  You already have it as part of visual (Vpython). 

3)  Introduction to Random numbers

Run the vpython demonstration program gas.py  Everything in this program is deterministic (governed by classical mechanics) EXCEPT how the initial positions and directions of the gas atoms are defined.  Look at the code for the program, notice the 4th line of imports and then scroll down to the line “for i in range(Natoms):”  This is where all the initial conditions are assigned.  Find the 4 places where the function “random()” is called and see if you can figure out what it does. 

Go to the python shell and try these commands:

From random import *
random()
random()

for j in range(20):
    print random()

randrange(1,10)
randrange(1,10)
randrange(1,10)

for j in range(20):
    print randrange(1,10)

Now open the python editor and make a program that places 10 balls at random positions on the screen.  Show me when you are done.

back to top

POWL - Class Activity, Sept. 10, 2004

1)  Open the pdf file Vpython_Intro and look through it.  This is another useful introduction to the graphics capabilities that you may want to use as a reference.

2)  Open Python and go to Help, Python Docs, Tutorial.  Look at sections 3.2 (on “while”) and section 4.2 (on “for”).  We will do control loops in detail a little later, but this information will help you get started with some useful programming in the meantime.

3)  For those of you who are interested in heavy-duty Python handling, go back to Python Docs and look at the “Installing Python Modules” document.  Section 4.1 on the search path is useful for understanding how Python searches the folder structure.

4)  Programming activity:  today we will work with modifications of the program orbit.py.  

Open the Python editor (IDLE) and open orbit.py. 

Add a comment to the start of the program indicating that you are modifying orbit.py, your name and the date

a)  make the orbit show up in the xy plane immediately by changing giant.p= vector (0,-1e4,0)*giant.mass

b)  experiment with dt

make dt 10x smaller – run the program and see what happens
make dt 10x bigger –   “
make dt another 10x bigger, and also change rate(100) to rate(10) – run the program and see what happens

set dt and rate back to the original values

c)  experiment with the while control

change the command “while 1:”  to “while giant.p.y <0”
run the program and see what  happens

try some other variations, such as “while giant.p.y>-2e26
                        “while dwarf.pos.y>-2e11

Make sure you understand what is happening, and try some other test numbers.

d)  experiment with changing “while” to “for”

change the command “while 1” to “for i in range(500)”
run the program and see what happens

Use your ability to change the range statement to find out exactly what the period of the orbit is.  (translation:  find out how many time steps it takes to make the planets go around exactly once).

e)  Calculate the initial energy of the system

    E = p(dwarf)**2/(2m) + p(giant)**2/(2M) -GmM/r

You will add lines of code BEFORE the “for” or “while” loop. 

To raise a number to a power in a program, use **,  that is x2 is expressed as x**2.  Be careful with entering the equations, you may need to use parentheses to make sure the order of operations is what you want. 

For the momenta you will need to use the magnitude of the vectors: 

|pdwarf| = mag(dwarf.p), etc.

also the value of r is the distance between the two planets so you will use:  |r| = mag(dwarf.pos-giant.pos)

Have your program print the calculated value to the screen:

print “The total energy of the system is %10.3E J” %energy

Show me your program running with energy output, and exactly one cycle of orbit.

back to top

POWL - Class Activity, Sept. 3, 2004

1)  Open Python and go to Help, Python Docs, Library Reference, Built-in functions

These functions are always available for use in Python – when you want to do some specific thing, look here first to see if the function exists already.  However, it turns out that many things that you would like to do are not automatically loaded with Python.  For instance:

Open the  python shell and try the following,

Type:   pi 
Type:   cos(1.57)

But…there are modules available to do almost anything you want.  (Vpython functions are imported through a module called visual). 

2)  Go back to Python Docs, Global module index, pick “math” from the index.

These are math functions available if you import the math module.  Work through the following demonstration in the python shell:

Type:  from math import *
Type:  pi
Type: cos(1.57)

Now try complex numbers:
Type:  sqrt(-1)

Now type:  from cmath import *
Type:  sqrt(-1)
Type:  4+3j
Type:  (4+3j)*j
Type:  (4+3j)*1j

3)  Activity for today involves working with Vpython.

Refer to your print out of the Vpython documentation, or open it from the help menu. 

Type: from visual import *
Type:  rod=cylinder(pos=(0,0,0))

Test all the functions (pos, axis, radius, color, etc.) listed for the cylinder function.

Now go to the editor (if you can’t find the window, in the shell go to file, and then new window).

Write a small program to draw 4 spheres, positioned at the corners of a square, with a different color for each sphere.  


decoration

back to top

Programming Project

Programming Projec:   Due Monday, Dec. 6
                                      Topic approval, no later than  Monday, October 18
                                       Approach approval no later than Monday, Nov. 1

Assignment:  Choose a physical science problem that involves either multiple interacting objects, or stochastic processes, and write a computer program to calculate the behavior of the system and display the results effectively.  Your program output should make it easy for the user to understand your problem and the significance of the result.  You should clearly indicate at least one independent variable in the problem, document the effects of changing the values for that variable in the program and explain the significance of the result.
As a required part of your project,  you will describe and demonstrate your program in a 10 minute presentation for the class during the final week of classes.

Program Specifications:
The program should illustrate your ability to do the following:
a)  define and use functions
b)  define and use classes and associated methods (use at least one)
c) use multi-dimensional lists and nested loops (for many-body problem)
OR
 Calculate statistical averages and distributions (for stochastic problem)
d)  create and use effective input/output screens, including graphics
e)  design, use and document test cases to insure the correct functioning of your program
To do an interesting problem will probably require about 50-100 lines of code* (documentation statements don’t count as lines of code).  The maximum length should not be more than 150 lines of code.

Programming Approach:
Use the 6 steps of software development :
 1)  Specify the problem requirements (and see me for topic approval)
 2)  Analyze the problem
 3)  Design the algorithm (and see me for approach approval)
 4)  Implement the algorithm
 5)  Test and Verify
 6)  Document thoroughly and CLEARLY

*If you modify an exisiting demo or course program, you should clearly indicate with documentation statements what part of the code is original (e.g. you wrote it) and what parts of the code came from other sources.

back to top

decoration

Exams 


Exam #1
Exam will be a practical programming exercise, held in the POWL lab.

Exam Rules:

    Blank floppy disks will be provided.
    Students may use any documentation or files on the course server.
    Students may not use books, notes or any contents of their own floppy disk.

Exam Format:

 Students will be asked to write a Python program that
a)      reads in user-supplied initial conditions for a specified force problem
b)      creates lists corresponding to time, position, speed and acceleration
c)      fills the lists with values calculated using the Euler algorithm
d)      performs a specified analysis on the lists
e)      reports the results in a prescribed format

Sample Exam#1 Problem:

An object of mass m=1.50 kg is subject to a one-dimensional force F = -kx - bv, where k = 8.0N/m and b = 0.46 kg/s are positive constants.  Write* a program that:

a)  Prints a title and asks for input of the initial velocity vo and position xo.
b)  Uses the Euler method to solve the equations of motion, and creates lists with the time, position, velocity and acceleration of the object.  Solve the motion using a time interval of dt = 0.02*sqrt(k/m)/(2.0*pi).  Run the solution until total time is t = 1000*dt. 
c)  Prints out a neat table (with a header) of t, x, v and a for every 50th time interval.
d)  Sets up a conditional test loop to find the times in the calculated list (this will not be exact) when the position passes through a local maximum or a minimum  Print out a neat table of the time and positions found.

*Suggestion:  write and debug  the program for part a) first.  Then add part b, etc.


For examples of previous exams, see old web pages from Phys 165 in 2001 and 2003, at:

http://www.physics.umd.edu/courses/Phys165/index.html

back to top


Practice problem for exam # 2

The interactions between Noble Gases can be approximated with a force function based on the Lennard-Jones potential. 

Find the file e2data.dat on the course server.  This is a “pickled” output.  The output contains two objects, an integer and a list of vectors.  The integer equals the length of the list.

1)  Write a program that reads in (using pickle) the list of vectors, and uses them for the positions of a set of atoms.  The unit of length is meters.  Have your program print the positions of the first, the second, the 25th, the 26th, and the last atoms in the list. 

The atoms interact with each by a force that depends on the separation between atoms i and j, rij, according to the equation:

F(rij) = 24.0*eps*( (sig/rij)**7 – 2.0*(sig/rij)**13)

This force is attractive (or zero) for all atomic separations in this problem. 

2)  Write a function to output the vector force acting on atom i due to atom j with input of vectors ri and rj, and parameters eps and sig. 
Use the values eps =1.0e-21 (units Joules) and sig = 0.38 e-9 (units m) and have your program print the vector force on the first atom due to the second atom, the 25th atom, the 26th atom and the last atom in the list.  Make sure the direction of the vector force is correct. 

3)  Have your program calculate the NET vector force on the first atom, the 25th atom, the 26th atom and the last atom.   Print out the values of the vector forces neatly. 


***if you have problems with this, see homework solutions on the course server. 
back to top

Practice Final Exam Problem   (see also ps 11, problem 1)

Write a program that generates and displays a random walk on the surface of a sphere of radius 5 m.  (it’s not necessary to display the big sphere – just the walk)  Each step in the random walk should occur as an increment in either phi or theta, of size 0.01*360 degrees.  Have the program output the displacement vector (position at time t minus position at time zero) and its magnitude every 20 time steps for 1000 total walk steps.
Your program should define a class called Polarvector that creates three-component vectors in spherical-polar coordinates.  The class should:

a)  be initiated with attributes r, theta and phi, with theta and phi to be specified in degrees
b)  include a method to calculate x, y and z attributes, and a method to calculate the magnitude of a polarvector.
c)  include an operator overload method to calculate the vector difference between two polar vectors. 

Reminder:  the angle phi is measured downward from the z axis, and the angle theta is measured counter-clockwise from the x axis, so the relationship between rectangular and spherical polar coordinates is:
x=r*sin(phi)*cos(theta)
y=r*sin(phi)*sin(theta)
z=r*cos(phi).
Also remember that python calculates trig functions assuming the angles are in radians. 

  


decoration

back to top

Synopsis of Material Covered

I will periodically make a list of the topics we have covered in class and assignments and post it here. 

Recommended reference documentation:

VPython Reference Manual
Mathematical Modules from the Global Module Reference
Vpython_Intro.pdf
Python Tutorial, sections 3.2 (on “while”) and 4.2 (on “for”). 
Python Tutorial, sections 3.1.4, 5.1.1, 5.1.2 (on lists), 4.3 (the range function)
Python Tutorial, sections 4.1 and 4.4 (if and break commands)
Python Library Reference,     section 5.8 (pseudo-random numbers)
Python Library Reference,     section 2.3.6.4 (list operations)
Python Library Reference,     section 2.1  (built in functions)
                                               section 2.3.8 (file objects)
Python Tutorial,                     section  7.2 (files)
                                               section 7.2.2 (pickling)
Numarray, An Open Source Project (P. Greenfield, et al.)
Python Library Reference,    section 6.9 (time module)

Topics Nov. 12 - Nov. 24

       Conservation of energy in Euler calculation
         Error propagation
          Screen interactions

Topics  Oct. 22 - Nov. 12

Reading writing files, pickle method
Nested lists: creating, indexing, filling

Forces in multi-body systems
Classes:  attributes and methods
               equality and deepcopy
               operator overloading
Graphical User Interfaces (GUI)

Topics weeks of Oct. 11 - 22

Interpolation
Histograms
Color
Good principles in function definition - functions should be general and generalizable!
Opening files, directory structure
Writing files       

Topics Sept. 27 - Oct. 8

Functions:  definition, calling variables, default values, return, global constants
Augmented assignment: numbers, lists, strings
Variable swapping

Topics weeks of Sept. 24, Oct. 1

Random numbers, statistical averages and moments, random walk
If, elif, else control structure
Strings and Lists, their specialized operations
Introduction to 2-dimensional lists (matrices)

Topics week of Sept. 17

Euler method for solving equations of motion given a position dependent force
Logical comparisons
Recursion using for or while loops

Topics week of Sept. 10:

Gravitation and  orbits
Introduction to "for" and "while" control structures

Topics week of Sept. 3:

Documenting programs, including units on numerical values
First introduction to numerical analysis
First introduction to input/output commands
Review of gravitation/orbits
Importing modules into python (math module, cmath module, visual module)
Using Visual module

decoration

back to top
Programming Evaluation Criteria


Criterion
Possible Points
Per Program
Comments/documentation
     Title/name/date line in program
     Units documented in program
     Sections of code documented clearly
         a)  relevance to problem
         b)  explanation of code
15
Good programming practice
     Numerical values defined as variables
     Self-evident variable names
     Indentation and spacing , logical structure
     Use of functions, lists, …
     Debugging points in program
     Expandable program structure
15
Effective output:
     numbers include units,
     attention to significant figures
     column headers, column alignment
     graphical displays effective, labeled
15
Program function
    Complete – has all required features
    Runs with correct results
    Well-organized (expandable) code
55
Total Points 100

 
back to top
decoration

Mac Users

I suggest running Python 2.3 under OSX 10.3.  The installation instructions can be found at:
http://www.vpython.org/OSX_download.html

I don't recommend trying to run Python under OS 9 - the installation is difficult and there isn't a built-in edit window (IDLE program editor). 

 Python files are compatible between Mac and PC.  If you are moving files on a floppy disk, make sure it is PC formatted because otherwise you will not be able to use the disk on the PCs in the Physics OWL.

back to top

 
 
Copyright (2004) University of Maryland, College Park. All rights reserved. 
Permission to redistribute the contents without alteration is granted to
educational institutionsfor non-profit administrative
or educational purposes if proper credit is given to
the University of Maryland, College Park as the source.