Maybe you are a physicist and maybe you want to use python. Well, then this is for you. OK, let’s just jump right in.
Introduction to Functions
What is a function in python? Honestly, it’s a lot like a mathematical function. So, let’s just start with a function (totally just making up something here).
This basically like a box that you feed a number into and it spits out some other number. But I assume you already know about mathematical functions. You want to know about python functions.
Well, here’s the surprise — at a certain level, a python function is the same as a math function. OK, let’s just jump into python. Technically, I’m going to be using Glowscript. This is an online version of python with some extra stuff added (like vectors, graphing, and 3D visualizations). Trust me, it’s great.
So, let’s make a python function that does the same thing as this mathematical function. Here is the code and then I will make some comments (also, the code is online too so you can edit it and stuff).
Here is the output when you run it.
Now for some comments.
- Line 1 is just there to make this a GlowScript program — this is not a normal python thing. Don’t change this.
- Line 3 defines the function. You need to start with
defand then give it a unique name (you can’t use a reserved name like
sqrtsince that’s already used) — but just plain “f” will work. Next you need to tell the function what variables (and how many) you are going to send to it. Finally, you need to end that first line with a colon. Everything that follows and is tab-indented is part of the function.
- Inside the function, you can make more variables. You don’t have to do it like this, but I like to create a temporary variable (is it surprising that I called it
- Line 4 takes the variable x and just performs the mathematical function. Notice that “squared” in python is **, not ^.
- Line 5 ends the function. Using
returntells the function what number to send back.
- In lines 7 and 8, I just call the function with two different values.
Oh, be careful about global vs. local variables. It’s possible to define a variable outside of the function and then use it inside the function (global). However, if you define it inside the function, it only works inside the function (local). Just be careful. When in doubt, test it out.
Here’s a cool trick too — you can call a function with a variable. Check this out.
Yes, both lines print the same thing — 22. Wait! How about something even cooler? What if I have a second function:
I can define that as another python function and then use that to find f(g(3)) — composition of functions.
Graphing a Function
OK, but who cares about just printing out values of functions? What if I use this to make a plot of f(x)? Yes, let’s do that. Reminder, here is my post about graphing in python.
Here is my code for plotting the function f(x) from x = 0 to x = 5.
With the following output.
Notice that I changed the variable in the function to
xt? That’s just to make sure the value of x doesn’t get mixed with the value in the function. Yes, I got scared.
More Complicated Functions
OK, how about a more complicated function? What if I want to find the gravitational field vector at some position due to a planet at some other location? Here’s a diagram showing the important idea for that calculation.
Notice that I didn’t put the planet at the origin. Overall, I am going to need the following stuff to find the gravitational field.
- The mass of the planet (M). I don’t need the radius of the planet if I assume that the location of the gravitational field is outside of the surface.
- The vector position of the planet (rp).
- The vector location of the gravitational field (ro) — the observation location.
I don’t need to send the value of G (the universal gravitational constant) since that doesn’t change. Here’s what I get for this function (code here).
So, you see that you can send in multiple things into the function — vectors and scalars and the same time. That’s pretty awesome. Of course this function uses other functions. There is the built in GlowScript function
norm() that finds the magnitude and normal vector for some vector input. On top of that, you can have a vector output. Cool.
Functions with Multiple Outputs
You can also have more than one output. Check out this function. It takes two vectors and returns three things:
- The sum of the two vectors.
- The dot product of the two vectors.
- The cross product of the two vectors.
Notice that the output is a list of the three values (two vectors and a scalar). I’m going to write a post about lists later, but for now let’s just do this.
Here I assign the output of the function to a temporary variable (I call it
result) and then I can “access” the different parts of the answer by using a list index. The first item in the list is
result and then the second one is
result and so on. Yes, you could just skip the temp variable and do something like this:
But then if you want the dot product, you would have to run the function again. That’s not a big deal here, but what if it’s a super complicated function that takes a while to run? You don’t want to do that — better to have the temp output.
Functions Useful for Physics
How about something more physics-like? Suppose I have a ball that is launched at some angle with some velocity at some height above the ground? (no air resistance). How far does it travel?
OK, let’s do this as just a numerical calculation using the Euler method here is a refresher video:
That example shows how to make a 3D model of projectile motion, but let’s just get the numbers. Here is my code.
There’s not much to say here except that it seems to be working. Oh, even though the mass of the object doesn’t matter I put it in there anyway.
Now let’s turn this into a function. For this function, I want to be able to input: the launch velocity, the launch angle, the starting height. For the output, I want the final position AND the time (just because). Here’s what that looks like.
I’m using the same initial values as my non-function version of this calculation, so it’s really no big deal. But wait! Now for the magic of functions. I’m going to use this function to find the launch angle that gives the largest range (final horizontal distance) — no, it’s not 45 degrees (that’s only the max range on flat ground).
So, here is the plan.
- Start with a fixed launch velocity (5 m/s) and a fixed height (2.1 meters).
- Begin with a launch angle of 0 degrees. Use the function to find the range.
- Increase the launch angle by some small amount and find the range again.
- Use all these range values for different angles to make a plot of range vs. launch angle.
- From that graph, I should be able to find the max-range launch angle.
Let’s do it. Here is what I get. This is only the new part (the prange function is still there).
From this, I get a maximum range at a launch angle of about 30 degrees (see — it’s not 45 degrees). Awesome right?
OK, I think that’s enough for you to start with function in python. Here are somethings for you to try (yes, it’s homework).
- What about a baseball launched with a speed of 50 m/s? What angle gives the maximum range on flat ground WITH AIR RESISTANCE? Ha. See, you thought you could do the max range problem above as a max-min problem (you can), but for motion with air resistance you have to do it with a function.
- Create a function that solves the quadratic equation. Warning: you need to consider the situation in which there are no real roots.
- For your second semester of physics (electric and magnetic fields), make a function to find the electric field at some location due to multiple electric charges. Use this function to map out the electric field in some region.
Since we are talking about projectile motion range, here is a calculation of a the max-range launch angle for this GIANT WWII canon. The projectile goes so high that you have to take into account the decrease in the density of air.