## Programming Games with Python

I’ll be giving a talk at the Science Olympiad Nationals being held here at UW-Stout on gaming physics engines. I thought I’d put up a few resources related to my talk and add some resources on how to get started programming games using Python.

Why Python? Python is an easy language to learn, it is easy to code, and it is very easy to read (which is a huge plus for me as an instructor). Not many commercial games are written in Python but some do use elements of Python as part of their scripting engine. Python is a good place to start learning how to program before moving on to more challenging languages. As a scientist I use Python as my primary programming language because many of the tools I need on a day-to-day basis are available in Python.

Both Udacity and Coursera have free courses available that will help you learn Python. Keep in mind that in addition to a paid version of the courses you can usually take the courses for free.

To learn how to program games in Python I recommend Invent Your Own Computer Games with Python and Making Games with Python and Pygame. Both are available for free or you can pay to get a physical copy of the books. These two books work well together and I recommend my students take a look at both when getting started. I also recommend looking at the website Programming Arcade Games with Python and Pygame as another great place to get tips and tricks for starting out.

More general books for learning how to program Python are available at Learning Python the Hard Way and How to Think Like a Computer Scientist: Learn with Python. Both are great resources for beginners.

Good Luck

Programs from my Science Olympiad talk:

Here are links to the programs I demonstrated during my talk at Science Olympiad Nationals. This folder on the www.glowscript.ord contains all of my publicly available VPython files, which you are free to copy and use for your own purposes.

## List of SBG Resources

There are quite a few other bloggers that I relied on to get started with learning objectives based grading. Here is a good collection of the links I’ve found invaluable in getting started.

Blogs on SBG

Shawn Cornally at ThinkThankThunk
Frank Noschese at Action-Reaction
Kelly O’Shea at Physics! Blog!
Always Formative
Pretty Good Physics Standards Based Grading
Dan Myers at dy/dan
Ian Beatty at Beatty Web

SBG Galas

One of the richest resources I’ve found have been the SBG Galas (which no longer seem to occur). Here are links to some of the earlier galas

## Relativity – Part I: Why is Relativity Exciting to Study?

2015 is the 100th anniversary of Einstein’s general theory of relativity.  In particular, on November 25, 1915, Einstein published the gravitational field equations of general relativity.  Ten years prior, in 1905, Einstein published his special theory of relativity.  To celebrate the 100th anniversary I’ll be writing a series of posts on special and general relativity.  These posts are based on a workshop I gave on special relativity for K-12 instructors this summer (you can find a link to the activities here.
The question running through you head right now is probably ‘what is the difference between special and general relativity?’  What’s so ‘special’ about special relativity?  Special relativity relates to a specific case (or special case in science-speak).  The special theory only deals with objects moving in straight lines at constant velocity with no external forces acting on the objects.  Although this may sound to be limited, the conclusions you can draw from this specific case are mind-boggling.  In particular special relativity requires us to rethink our notions of what space and time represent.  We’ll find that special relativity requires that we think of space and time as being a single thing called spacetime (but that is for a later post).  General relativity doesn’t place any limitations on how the objects or moving or what forces are present so it is more general than the special case.  General relativity tells us what the geometry  of spacetime looks like.  Mass actually bends spacetime, which results in the gravitational force

Spacetime curvature“. Licensed under CC BY-SA 3.0 via Commons.

## Conclusions of Relativity

These conclusions are loosely stated and may not be completely correct, but they at least convey the broad ideas.  In later posts I’ll discuss what is wrong with some of these statements.  Hopefully they will give you a flavor for what the theories of relativity say.

### Special Relativity

1) Moving clocks run slow (time goes more slowly for moving objects)
2) Moving objects are shorter along the direction of motion
3) No objects can move faster than the speed of light
4) Mass and energy are equivalent
5) Fast moving objects gain mass
6) Moving electric fields can look like magnetic fields and moving magnetic fields can look like electric fields

### General Relativity

1) Mass of objects bends spacetime, which is results in the gravitational force
2) Gravity causes time to move slower
3) Since masses bend spacetime, the path of light will bend near large masses
4) If an object is massive enough, light can be trapped near the massive object (black holes)

## Why is Relativity Interesting?

### GPS

The most common reason given for why relativity is relevant is the global positions system (GPS) used by our phones and cars to help us navigate.  Global positioning depends on our phone receiving a time-stamped signal from several orbiting satellites and, based on the differences in travel times, determining where we are relative to the satellites.  I’ll give you a simplistic idea of how GPS works to show why times are so important.  Imagine your phone gets two time signals from different satellites that differ by 1 microsecond (a thousandth thousandth of a second).  This tells your phone that you are 1 microsecond closer to one satellite than the other.  Since light travels at a constant speed of $3 \times 10^8$ meters per second so you’d be $(3\times 10^8\ m/s) (1 \text{ microsecond}) = 300\ m)$ This doesn’t tell you exactly where you are but, since the satellite positions relative to each other are known, it does give you are range of positions.  If your phone can get a time signal from two other satellites it can tell you where you are located (For the mathematically inclined, four satellites are needed to determine the four unknown quantities, x-position, y-position, z-position, and time.  If you have a highly-accurate atomic clock handy you would only need three satellites).  This is why accurate times are so crucial to GPS – if your clock is off by a microsecond your position will be off by $300\ m$ (approximately three football field lengths), which would cause trouble if you are trying to navigate in a dense city.  Since the satellites are orbiting and moving quickly, special relativity says that a phone on Earth will see the satellite clocks running slow relative to a clock on the Earth.  General relativity says that since the satellites are far from the surface of the Earth, the gravitational force is less so the satellite clocks run faster than clocks on the surface of the Earth. Both of these effects need to be calculated to give accurate position readings.  It turns out that the effects of general relativity are much larger than the effects of special relativity.  General relativity predicts satellites will get ahead of ground-based clocks by 45 microseconds each day but special relativity predicts a delay of 7 microseconds each day1.

### Electromagnets

You can explain how electromagnets and generators work using relativity.  I’ll explain more in a later post but relativity brings the electric and magnetic forces together in a similar way to how relativity brings space and time together.

### Color of Gold and Why Mercury is Liquid at Room Temperature

For heavier elements on the periodic table, the fact that particles masses increase as velocities increase starts to play a noticeable effect.  The electrons near the nucleus have average speeds that are a significant fraction of the speed of light (e.g. for mercury, the inner-most electron has an average radial speed of 58% the speed of light) so the mass of these electrons increase as a result.  The larger masses result in the orbits of the electrons being smaller, which affects how the atoms reflect light (e.g. the color of gold) or how the atoms interact with each other (e.g. why mercury remains liquid at room temperature)2.

### Blackholes

Face it, black holes are awesome!  Something that bends light and time is fun to think about.  There is still a lot we don’t know about black holes, such as what happens inside black holes (although Interstellar seems to indicate there is a giant library inside) and many they are an exciting area of theoretical research.

### Gateway to Mathematical Models of Physics

Here is what I consider the most exciting aspect of special relativity and this is what motivated me to write this series of posts.  With a knowledge of the Pythagorean theorem and a little algebra you can derive the results that show space and time become intertwined, that how we think of distance and time is not compatible with the way the theory predicts (and experiments support).  Given how mind-bending the results are, I think the mathematics involved are relatively easy to grasp.  Usually the mathematics associated with many theories ( quantum mechanics comes to mind) are fairly involved and go beyond what most folks pick up in high school or college math classes.  I’ll devote the next few posts to exploring how the conclusions of special relativity can be derived from two simple assumptions.  After that I’ll talk about general relativity.

#### Footnotes

1.100 Years of General Relativity at Nasa.gov
2. Why is Mercury a Liquid or Why Do Relativistic Effects Not Get into Chemistry Textbooks on Researchgate.net

## Special Relativity for K12 Students

I put the attached activity together for a group of K12 instructors. I would expect that a high school physics student should be able to complete the entire packet and lower grades can work through parts of the activity. Feel free to download and share the activities. I hope to make updates to the packet and eventually put together a version in Microsoft Word so it is easy to edit. Stop back for more updates.

Introduction to Special Relativity for High School

## Intro to Electromagnetism – Next Gen Science Standards Workshop

Last summer a group of faculty at UW-Stout hosted a group of high school instructors from the area to work on activities related to the Next Generation Science Standards. I’ve attached the activity I developed for the workshop. Feel free to download this and modify it to your own uses. If you post a different version online somewhere send me the link so I can share it.

Introduction to Electromagnetism – v3

## Energy vs. Momentum – The Veritasium Video

A couple of days ago I noticed a blog post from Chad Orzel entitled How Deep Does Veritasium’s Bullet Go?.  It links to a video by Veritasium that asks which block goes higher, one shot with a bullet on center, or one shot with a bullet off-center.  Take a look at the video.

Before you go any further make an educated guess as to which block goes higher.  Rhett Allain at Dot Physics  goes through an analysis of what happens here.  Since Chad and Rhett did a pretty good job covering the physics I want to talk about this from a broader perspective.  Most of the answers I saw on different websites talked about energy conservation and only a couple actually mentioned momentum conservation.  I’m not completely sure why energy dominated the conversation, but I bet it has to do with the fact that more time is spent on energy than momentum in most physics curricula, and people seem more comfortable with energy, even though I think most students have a stronger conceptual grasp of momentum than of energy.

Momentum $\overrightarrow{p}$ is defined as the mass $m$ of an object multiplied by the velocity $\overrightarrow{v}$ of the object (for this post we’ll assume we are dealing with a classical system moving at much less than the speed of light) or $\overrightarrow{p} = m \overrightarrow{v}$  The arrow over the $p$ and $v$ mean that both of these are vectors.  A vector contains two pieces of information; how much, and which way.  A velocity vector tells you how fast the object moves and which way.  The momentum vector tells you how much momentum the object has and which way the momentum is pointing.  Energy, on the other hand, is a scalar quantity, which only provides information about how much, and has no directional component to it.  The kinetic energy $K$ of an object is defined as one half of the object’s mass $m$ times the magnitude of the velocity $v$ squared or $K = \frac{1}{2} mv^2$.  Notice than none of the terms in this equation are vectors (the magnitude of the velocity, or speed, is required, rather than the velocity, which is a vector).

The fact that energy is a scalar quantity makes it much easier to use than a vector equation.  If you’ve ever dealt with vectors you will remember that you need to keep track of three pieces of information, instead of the single number needed for a scalar.  The fact that there is no direction associated with energy which simplifies the math considerably.  However, to work with energy you have to throw out that piece of information that tells you “which way” which means you loose some idea about what your system will do.  Momentum requires you to keep track of more information, which means more calculations are needed.

Here is a simple example of the limitations of energy.  If I know the speed of a ball that is launched in the air I can use energy conservation to calculate the maximum height the ball could reach.  However, if the ball is launched at a $45^{\circ}$ this calculation won’t tell me how high the ball actually goes without a few extra calculations.  If I used momentum instead, I could figure out how high the ball goes, where it reaches its peak height, where it will land, and how long it was in the air.  Of course this will take a few more calculations to do, but all of the relevant information is retained.

The information loss yields another important (potential) limitation on energy.  Since energy does not conserve information about the direction of motion associated with energy, whenever two objects collide, like the bullet and block in this problem, the kinetic energy is able to split up into different directions.  In particular, collisions can cause the macroscopic kinetic energy of the incoming bullet to be transformed into internal energy of the system, either by heating things up or deforming the objects.  This means that it can look like energy seems to disappear altogether.  The energy is still there, it is conserved, but it is hidden from our eyes inside the block.

Momentum, with its directional nature, is much harder to hide (but not impossible*).  This means that however much upward momentum the system originally has (i.e. the bullet shot upwards) is exactly how much momentum we will be able to see after the collision (i.e. the block with the bullet embedded).  Since the bullet in both cases has the same initial upward momentum, both blocks after the collision will have the same final momentum, which means that must reach the same maximum height.

So what is the take-away message from all of this?  Energy, while useful, has its limitations.  You throw away useful information about the system when you start thinking in terms of energy.  Energy will help you figure out the limits of, say, how high the system might go, but it won’t always tell you exactly what will happen.  Momentum will give you a more complete view of what is really going on and is more likely to allow you to determine exactly how the system will move.  Be careful when using energy and make sure you are aware of the limitations of your tools.

* It is left as an exercise for the reader (or a future blog post) to figure out how momentum might seem to disappear from view
** It’s actually about the center of mass of the wood block and bullet system, but given the low mass of the bullet these two points are pretty close together.
Posted in Learning Physics | Tagged , | 4 Comments

## Why is Multiplication Harder than Addition?

I’m in the process of writing a couple of blog posts about slide rules, and an interesting questions occurred to me, which spawned this post. Why is addition so much easier than multiplication? The power of slide rules comes from the fact that multiplying two numbers together is equivalent to adding two logarithms. The slide rules made life easier for scientists, engineers, and financiers for centuries by reducing multiplication problems down to simple addition.

I decided to figure out how many operations adding and multiplying takes. The model I’m using is based on Feynman’s model of a simple computer from his book Feynman Lectures on Computation. Imagine that you have a person who doesn’t know how to add or multiply numbers, but they are very organized and very good at following directions. They have a sheet of paper in front of them with the problem they are trying to solve (either adding or multiplying numbers) and the only tool they have is an addition table which allows them to look up the answer to x+y for all numbers between 0 and 9. Additionally, they have a multiplication table for all numbers between 0 and 9. Every time they have to access the additional table or multiplication table it is considered a single operation. The question I want to know is, in general, how many operations does it take to add or multiply a series of numbers together? I’m sure one of my mathematician friends could rattle the answer off the top of their head, but I wanted to see if I could figure it out on my own.

Let’s start simple, with two 2 digit numbers (to hopefully avoid confusion I’ll use numerals to denote the number of digits and words to denote the number of numbers).

$\begin{array}{@{}cr} & 31 \\ + & 17 \\ \cline{2-2} & \\ \end{array}$

The computer (note that the word computer used to refer to a person who calculates numbers) pulls out his chart to look up $1 + 7 = 8$ and writes 8 down in the first column.
$\begin{array}{@{}cr} & 31 \\ + & 17 \\ \cline{2-2} & \ 8 \end{array}$
Next he looks up $3 + 1 = 4$ and writes that down.
$\begin{array}{@{}cr} & 31 \\ + & 17 \\ \cline{2-2} & 48 \end{array}$

Since the computer used the look-up tables twice, it took two operations to add two 2 digits numbers. Let’s extrapolate to adding more numbers. For simplicity, I’ll assume that all numbers that are being added have the same number of digits. If you add three 2 digit numbers together it ends up taking a total of $3\times 2 = 6$ operations. Remember that your addition tables only allow you to add two digits together at a time so you will need to add the first two numbers together first, then add the third number to this results.
$\begin{array}{@{}cr} & 31 \\ + & 17 \\ + & 12 \\ \cline{2-2} & \end{array}$
The first two numbers give you 48 and took four operations, and adding 12 to 48 takes another two operations, for a total of six.

We can extrapolate to see that adding M 2 digit numbers together takes a total of 2M operations. You can also easily see that if you expand this even further to consider numbers with N digits, it will take $N\times M$ operations to add those numbers together. This is actually a lower bound on the number of operations, because frequently you will add two numbers and get something larger than 10, which requires you to add a carry digit to the next column over. It turns out that, on average, adding M numbers with N digits, it will take $\left( M + \frac{1}{2} \right) N$ operations.

## Multiplication

Does multiplication take more operations to complete? Let’s take a look.
$\begin{array}{@{}cr} & 13 \\ \times & 21 \\ \cline{2-2} & \end{array}$

Our computer starts off by looking up $1\times3 = 3$ and then $1\times1 =1$. The next step is then looking up $2\times3 = 6$ and $2\times 1 = 2$ so we’ve completed four operations and have the following results:
$\begin{array}{@{}cr} & 13 \\ \times & 21 \\ \cline{2-2} & 13 \\ & 260 \\ \end{array}$

Now we need to add the two numbers together. The number of operations is either one or three, depending on whether you count addition by zero as an operation. I’m going to count it as an operation since we assume our computer doesn’t understand anything about numbers and needs to look up even this simple process. This means that multiplying two 2 digit numbers together takes seven operations, which is clearly larger than the four operations taken to add two 2 digit numbers together. To come up with an equation for multiplying more numbers with more digits we need to consider that adding another digit means you now have to multiply that one digit by all of the other digits in the other number. Multiplying two 2 digit numbers yields $2^2 = 4$ multiplication operations so multiplying two N digit numbers will yield $N^2$ operations. Once you are done multiplying the digits together, you have two numbers with 2N digits that you need to add together so these combining two N digit numbers takes roughly $N^2 + 4N$ operations. Note that for N = 2 the equations says that it should take 8 operations but I only counted 7 in my example. This is because I assumed two 2 digit numbers yields a four digit product, which only occurs if all of the digits are larger than 3.

Things start to get a little tricky when I try to extend this to multiple numbers so I’m going to leave that for another day. The end message is that the number of operations to multiply numbers together scales as $N^2$ while addition scales as $N$. As the number of digits increases, multiplication rapidly starts taking more individual operations to get a results. This means that if you can somehow simplify a multiplication problem so it only requires additions, you might be able to save some time and effort. Stay tuned for my upcoming posts on slide rules.

Posted in Just for Fun | | 2 Comments