VPython Functions

From Physics Book
Jump to navigation Jump to search

Introduction to functions in Python and applying them to write shorter and more understandable code. Assumes that VPython is installed and you understand the basics of programming in Python.


Functions at a high level are used to perform a certain task. Functions can accept a number of inputs (also "arguments" or "parameters") and can give back 0 or 1 output values. Furthermore, they make code much easier to understand by encapsulating a task in a single line of code instead of being repeated over and over again.

Functions always start with def, which is short for define, used to define a word with a piece of code, not data. • Function is like a box of commands • Functions can take inputs • The way we pass those inputs is by putting them in parenthesis Functions can return objects (outputs)

def sayHello():
  print "Hello, world"

This is a simple function that defines the variable "sayHello" to return the phrase "Hello, world" (note that the parenthesis will not be printed. Only the Hello, world portion will be printed).

• Note that python uses indent to consider what is under a command. If print "Hello, world" is not indented, then it will not be a part of the function sayHello().

Automating problems with VPython

1.When you are trying to simulate multi-particle systems that require hundreds of calculations
2.Sometimes when you are having trouble understanding homework problems solving it with python can help you understand hard to grasp concepts.

Basic of Functions

Basic Python function syntax

Functions can be defined with the keyword "def" followed by the function name and a colon and a parenthesis. The variable that should be processed by the function goes Inside the parenthesis.

def madlib(name, noun1, noun2, verb):
  result = name + " was looking at his " + noun1 + " when a " + noun2 + " " + verb + " nearby."
  print result

This is a simple function that creates a madlib with the 4 variables that are given as inputs.

For example, if Sally was inputed as the name, lunch as noun1, pterodactyl as noun2, and flew as the verb, the the function will return the phrase Sally was looking at his lunch when a pterodactyl flew nearby

>>> madlib("Sally", "lunch", "pterodactyl", "flew")

Sally was looking at his lunch when a pterodactyl flew nearby. >>>

Returning the output given by a function

When a function takes an input and gives an output such as print in the madlib example, you cannot refer back to the output phrase Sally was looking at his lunch when a pterodactyl flew nearby. If you would like to use this phrase again, then a function called return is needed. When return is added at the end of a function, the output is passed back to the caller, which means that you can refer to the output now.

def madlib(name, noun1, noun2, verb):
  result = name + " was looking at his " + noun1 + " when a " + noun2 + " " + verb + " nearby."
  print result
  return result

With this new code, if you need to refer to the sentence Sally was looking at his lunch when a pterodactyl flew nearby., you can do so by by typing in result.

Example function

# This function adds three numbers together and gives back the result using the return keyword
def addNumbers(a, b, c):
    return a + b + c

Conditional Statement

Lets say you have the following code:

# This function prints every letter in the input
def printLetters(string):
 for letter in string:
  print letter

What if your evil TA asks you to only print the vowel letters given in the input? This means that you need to add a condition to your function where the print function only works if the letter is a vowel. This can be done by using conditional statement.

Condtional statement starts with if.

def justvowels(string):
 for letter in string:
   if letter in "aeiou":
     print letter

Instead of printing every letter in the string, this code will only print if the letter in question can be found in the list "a,e,i,o,u"

Writing your own Functions

Writing a function for a task instead of copy and pasting code makes your program much easier to understand and debug.

When to write a function

1. You have a multi particle system
2. You are calculating multiple forces on multiple particles over each time step
3. You try not to use functions but keep running into errors or you see behaviors that don't look right. 

When NOT to write a function

1. You have a simple system consisting of one particle and less than 3 or so forces
2. You only need to find 4 or 5 values pertaining to the kinematics of the object
3. You would be creating more trouble if you were writing function. 

For example, to write a function that calculates the electric field created by a point charge, we first find the formula.

[math]\displaystyle{ \overrightarrow{E}=\frac{1}{4πε_0} \frac{q}{|\overrightarrow{r}|^2} \hat r }[/math]

Then, we ask ourselves what we need in order to calculate the electric field?

  • [math]\displaystyle{ q }[/math] - the charge of the source
  • [math]\displaystyle{ \overrightarrow{r} }[/math] - the distance from the source to the electric field

[math]\displaystyle{ q }[/math] and [math]\displaystyle{ \overrightarrow{r} }[/math] will be the two arguments to our function which will look like this:

We start by creating a sphere for a point charge

p = sphere(pos=(-5e-11,0,0), radius=1e-11, color=color.red)

We also need to define the observation point where we calculate the electric field created by the point charge

obslocation = vector(1, 1, 1)

r, the distance between the obslocation and p

r = obslocation - p.pos
# We can now write a function that calculates the electric field at a point away from the charge
def electricField(q, r):
    electricConstant = 9e9
    rmag = sqrt((ap.x)**2+(ap.y)**2+(ap.z)**2)
    rhat = r / rmag
    E = (electricConstant * q / rmag**2)*rhat
    return E

The final code will look like this:

from __future__ import division
from visual import * 
p = sphere(pos=(-5e-11,0,0), radius=1e-11, color=color.red)
obslocation = vector(1, 1, 1)
r = obslocation - p.pos
def electricField(q, r):
    electricConstant = 9e9
    rmag = sqrt((ap.x)**2+(ap.y)**2+(ap.z)**2)
    rhat = r / rmag
    E = (electricConstant * q / rmag**2)*rhat
    return E

Using the function

We can apply functions to make our code shorter and easier to understand. Here is some example code that we will shorten with functions.

# Calculate the eletric field in two different places
charge = 1.6e-19
origin = vector(0,0,0)

point1 = vector(-10, 5, 15)
point2 = vector(20, -5, 12)

field1 = 9e9 * charge * point1.norm() / point1.mag2
field2 = 9e9 * charge * point2.norm() / point2.mag2

We can use a function in the last 2 lines to reduce the duplicated code to the following

field1 = electricField(charge, point1)
field2 = electricField(charge, point2)

Frequently Used Functions

VPython already has a few predefined functions for your ease. The following functions are available for working with vectors. To better illustrate these functions, let's say we have a vector called exVector.

exVector = vector(-10, 2 ,5)


# Calculates the magnitude of a vector
magExVector = mag(exVector)
print magExVector    # will print 11.357


# Calculates the magnitude squared of a vector
mag2ExVector = mag2(exVector)
print magExVector     # will print 129


# Calculates the unit vector of a vector
unitExVector = norm(exVector)
print unitExVector    # will print <-0.88, 0.17, 0.44>

dot(A, B)

# Calculates the scalar dot product between the two vectors
# exVector2 = vector(4, -2 ,8)
dotExVector = dot(exVector, exVector2)
print dotExVector     # will print 4

cross(A, B)

# Calculates the vector cross product between two vectors
# exVector2 = vector(4, -2 ,8)
crossExVector = cross(exVector, exVector2)
print crossExVector   # will print <26, 100, 12>

Example of using these common functions

Remember this code from the Writing your own Functions section?

def electricField(q, r):
    electricConstant = 9e9
    rmag = sqrt((ap.x)**2+(ap.y)**2+(ap.z)**2)
    rhat = r / rmag
    E = (electricConstant * q / rmag**2)*rhat
    return E

We can now simplify this code using some of the common functions listed in Frequently Used Functions section.

def electricField(q, r):
    electricConstant = 9e9
    E = electricConstant * q * r.norm() / r.mag2
    return E

It is also possible to skip defining the electricConstant * q * r.norm() / r.mag2 function and just return it.

def electricField(q, r):
    electricConstant = 9e9
    return electricConstant * q * r.norm() / r.mag2

Examples (Continued)

With Vpython it is possible to make graphs with ease by simply referencing a x axis and providing values that correspond with the x axis and have a value that can be plotted on the y axis.

To start you must import the necessary library:

from visual.graph import *

Then make a variable and declare what your x axis will be as well as color properties:

f1 = gcurve(color=color.cyan)

Every time you iterate through a loop use your index (most likely time elapsed) and a output value to add a point to your plot:




Functions are used everywhere in coding. For example, in computational media, coding is used to modify pictures, sounds, and movies. Of course, we now mostly rely on editing programs, but underneath that program, when you press a button to trace the edges of a picture, the program finds the function that it runs and returns the output. Such a code made look like this:

def luminance(pixel):
  r = getRed(pixel)
  g = getGreen(pixel)
  b = getBlue(pixel)
  return (r+g+b)/3
def edgeDetect(picture):
  for p in getPixels(picture):
    x = getX(p)	
    y = getY(p)
    if y < getHeight(picture) - 1 and x < getWidth(picture) - 1:
      botrt = getPixel(picture, x+1, y+1)
      thislum = luminance(p)
      brlum = luminance(botrt)
      if abs(brlum - thislum) > 8:
        setColor(p, blue)
      if abs(brlum - thislum) <= 8:
        setColor(p, white)

When this program is run with the picture on the left, the output is the picture on the right.

Connectedness(Taking Vpython core functions and creating a simulation)

Many Vpython assignments require the creation of functions that can calculate Momentum,impulse,velocity Position Below are some frequently used equations that can be adapted to certain problem sets:


def returnMomentum(vparticle,mparticle):
   momentum = vector(0,0,0)
   return vparticle*mparticle + momentum
momentum = returnMomentum(vparticle,mparticle)


# deltat = timestep in simulation. 
def returnImpulse(momentum,deltat):
   impulse = vector(0,0,0)
   return momentum*deltat
impulse = returnImpulse(momentum,deltat)


def returnVelocity(impulse,mparticle,velocity):
   velocity = vector(0,0,0)
   velocity = (impulse/mparticle)+velocity
   return velocity
velocity = returnVelocity(impulse,mparticle,velocity)


def returnPosition(position, velocity, deltat):
   position = vector(0,0,0)
   position = position + velocity*deltat
   return position
position = returnPosition(position, velocity , deltat)

Drag force

def returnDragforce(dragcoef,velocity,density,area):
   dragForce = dragcoef*((density*(velocity**2))/2)*area
   dragForce = dragForce * -1 * norm(velocity)
   return dragForce
dragForce = returnDragforce(dragcoef,velocity,density,area)

Bringing Everything Together

See also



VPython Basics

Further reading

VPython Common Errors and Troubleshooting

VPython Lists

Python standard function library.

Python Functions Tutorial