hansontechsolutions.com

A Physicist's Introduction to Python Functions for Physics

Written on

Chapter 1: Understanding Functions in Python

If you're a physicist interested in utilizing Python, you've come to the right place. Let's dive straight into the topic.

Introduction to Functions

What exactly is a function in Python? To put it simply, it's akin to a mathematical function. Imagine a function as a box where you input a number, and it produces another number in return. While you're likely familiar with mathematical functions, it's important to understand how they translate into Python.

At a fundamental level, Python functions operate similarly to their mathematical counterparts. I’ll be using GlowScript, an enhanced online version of Python that facilitates vector manipulation, graphing, and 3D visualizations—trust me, it’s fantastic.

Let’s create a Python function that mirrors a mathematical function. Here’s the code, along with some explanations (the code is available online for editing as well).

When executed, this code yields an output. The first line is specific to GlowScript; it isn’t standard Python, so leave it as is. The third line defines the function with the keyword def, followed by a unique name (avoid reserved names like sqrt—simply using f works). You will also specify the variables you intend to send to the function, concluding the line with a colon. Any subsequent lines that are indented belong to that function. Inside the function, you can define additional variables—like a temporary variable I’ve named temp.

In line four, the variable x undergoes a mathematical operation. Note that in Python, exponentiation is denoted by **, not ^. The function concludes in line five with a return statement, indicating the number to be sent back. In lines seven and eight, I invoke the function with two distinct values.

Be cautious about global versus local variables. You can define a variable outside the function and reference it within (global). However, a variable created inside the function is local to that function. It’s wise to test your assumptions.

Here’s a neat trick: you can call a function using a variable. Observe that both lines output the same result—22. But what if I define a second function?

This allows me to compose functions, calculating f(g(3)).

Graphing a Function

Now, you might wonder why merely printing function values is useful. Let’s plot f(x) instead! Refer to my previous post on graphing in Python for context. Below is the code to plot the function f(x) from x = 0 to x = 5, along with its output.

I adjusted the function variable to xt to avoid confusion with the input x.

More Complex Functions

What if I need to calculate the gravitational field vector at a specific point due to a planet at another location? Consider the following diagram illustrating this concept.

I don’t need the radius of the planet if I’m calculating the gravitational field outside its surface. The necessary inputs are:

  • The mass of the planet (M).
  • The vector position of the planet (rp).
  • The vector location of the gravitational field (ro) — the observation point.

I won’t send the value of G (the universal gravitational constant) since it remains constant. Here’s the code for this function.

You can input multiple values—both vectors and scalars—simultaneously, which is quite impressive. The function also utilizes built-in GlowScript functions like mag() and norm(), which compute magnitude and normalize vectors, respectively.

Functions with Multiple Outputs

It’s also possible to have multiple outputs. Check out this function that takes two vectors and returns three results: their sum, dot product, and cross product.

The outputs are formatted as a list containing the three values (two vectors and one scalar). You can assign this output to a temporary variable (let’s call it result) and access each part using list indexing. For example, the first item is result[0], followed by result[1], and so on. While you could directly access the elements, doing so may require running the function again, which can be inefficient for complex functions.

Functions Relevant to Physics

Let’s consider a practical physics application. Suppose a ball is launched at a specific angle and velocity from a certain height above the ground (ignoring air resistance). How far does it travel?

We'll perform a numerical calculation using the Euler method. Here’s a refresher video:

Now, let’s convert this into a function, allowing inputs for launch velocity, launch angle, and starting height. The output will include both the final position and time.

Using the same initial values as my non-function version, we’ll explore how to determine the launch angle that maximizes range (it’s not necessarily 45 degrees).

Here’s the plan:

  1. Start with a fixed launch velocity (5 m/s) and height (2.1 meters).
  2. Begin with a launch angle of 0 degrees and calculate the range.
  3. Increment the launch angle slightly and recalculate the range.
  4. Plot the range against the launch angle, identifying the angle that yields maximum range.

Here’s what I found: the optimal launch angle for maximum range is approximately 30 degrees (definitely not 45 degrees). Isn’t that fascinating?

As a starting point, here are some exercises for you to tackle:

  • Analyze a baseball launched at 50 m/s. Determine the angle that maximizes range on flat ground, accounting for air resistance.
  • Develop a function to solve the quadratic equation, being mindful of cases with no real roots.
  • For your second semester focusing on electric and magnetic fields, create a function to calculate the electric field at a point due to multiple electric charges. Use this to visualize the electric field in a given area.

Since we’re discussing projectile motion, consider the maximum range launch angle for a large WWII cannon, taking into account the decreasing air density at high altitudes.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Navigating Your Online Career: Avoid These Common Pitfalls

Discover how to sidestep common traps in your online career journey.

# Why the Coronavirus Will Always Be Relevant: A Historical Perspective

This article explores the history of coronaviruses, their persistence, and their impact on health globally.

Exploring the Intricate Universe Within Atoms

Delve into the fascinating world of atoms and their role as the fundamental building blocks of matter, revealing the secrets of the universe.