VPython: Difference between revisions

From Physics Book
Jump to navigation Jump to search
Tedpaek (talk | contribs)
No edit summary
Tag: Manual revert
Cjahn6 (talk | contribs)
I killed the python 2.7 / classic vpython stuff (deprecated since 2020), made it all python 3 + glowscript fixed the syntax everywhere: vector() not tuples, hat() not norm(), from vpython import, added the iterative prediction loop section because that's literally the whole point of vpython in 2211 and the old page didn't have it. Also added 3 worked examples: projectile, spring-mass, orbit. all with the momentum form like chabay/sherwood do it.
 
Line 1: Line 1:
VPython is a Python graphics module used for modeling objects in 3-dimensional space.  In the field of physics, this is especially useful for calculating and modeling complex relationships between objects and their properties.
'''<span style="font-size: 150%">Page edited by Caio — Spring 2026</span>'''


[[File:VPythonMagneticForceAnimated.gif|thumb|VPython modeling the magnetic force on a moving particle]]
VPython is a Python module that turns a few lines of code into a real-time, three-dimensional animation. It was built specifically for physics teaching: instead of solving differential equations on paper, you write a short loop that takes a small time step, applies Newton's second law, and watches the result move. This is the same iterative prediction strategy used throughout the ''Matter and Interactions'' curriculum (PHYS 2211/2212), which is why this course leans on VPython so heavily.


==Installation==
[[File:VPythonMagneticForceAnimated.gif|thumb|VPython animating the magnetic force on a moving charged particle]]


VPython is compatible with Windows, OSX, and Linux.  While there is an older VPython version available that supports Python 3, the Georgia Tech physics courses use Python 2 syntax so it is recommended to install the latest version of VPython as outlined below.
==Two Ways to Run VPython==


===Windows===
You have two reasonable options. New users should almost always start with GlowScript.
[[File:VPythonWindows.png|thumb|VPython running in Windows 7]]


1. Install [http://python.org/ftp/python/2.7.9/python-2.7.9.amd64.msi Python-2.7].
===GlowScript (recommended for this course)===


2. Download and install VPython from [http://sourceforge.net/projects/vpythonwx/files/6.11-release/VPython-Win-64-Py2.7-6.11.exe/download Sourceforge].
[https://www.glowscript.org/ GlowScript] is VPython in your browser. There is nothing to install; you sign in with a Google account, write your program in the online editor, and the simulation renders in the same page. This is also what [https://trinket.io/glowscript Trinket] uses behind the scenes when you embed simulations on a webpage like this one.


A GlowScript program begins with:


To troubleshoot any installation issues, look at the extensive [http://vpython.org/contents/download_windows.html VPython Windows installation guide].
<code>GlowScript 3.2 VPython</code>


===OSX===
That header is added automatically when you create a new program; you do not type it yourself.
[[File:VPythonOSX.png|thumb|VPython running in OSX 10.10]]


1. Install [https://www.python.org/ftp/python/2.7.9/python-2.7.9-macosx10.6.pkg Python-2.7].  This is required as the version of Python that Apple provides is not compatible.
===Local install with Python 3===


2. Download and install the VPython package from [http://sourceforge.net/projects/vpythonwx/files/6.11-release/VPython-Mac-Py2.7-6.11.dmg/download Sourceforge].
If you prefer to run VPython on your own machine — for example, because you want to integrate it with NumPy, Pandas, or a Jupyter notebook — install it with pip:


<code>pip install vpython</code>


To troubleshoot installation issues, see the extensive [http://vpython.org/contents/download_mac.html VPython Mac installation guide].
This works on Windows, macOS, and Linux as long as you have Python 3.7 or newer. Anaconda users can instead run:


===GNU/Linux===
<code>conda install -c vpython vpython</code>
[[File:VPythonUbuntu.png|thumb|VPython running in Ubuntu 15.04+]]


Some Linux distributions include VPython in their repositories.  For example, to install VPython in Ubuntu 15.04:
The local install opens its own browser tab to display the 3D scene; the Python program drives the simulation, and the browser is just the renderer.


<code>sudo apt-get install python-visual</code>
''Note: older versions of this page described installing Classic VPython 6 alongside Python 2.7. That version has been deprecated since 2020 and is no longer maintained. The instructions above replace it.''


If your Linux distribution's repository does not have the latest version of VPython, you can run the Windows version using [https://www.winehq.org/ Wine].  The [http://vpython.org/contents/download_linux.html VPython Linux installation guide] contains detailed instructions.
==Vectors: the One Concept That Matters Most==


==Getting started with VPython==
Almost every physics quantity in VPython is a vector — position, velocity, momentum, force, magnetic field. You construct a vector with:
The easiest way to use VPython is with VIDLE.  VIDLE is a development environment and is the most useful for editing and running code.  To start, open the VIDLE application (it may be called something like VIDLE-Py2.7).  A blank file should open.  Type the following two lines in:


<code>from __future__ import division
<code>v = vector(3, 0, -2)</code>


from visual import *</code>
or, for short:


The first line tells Python to not use integer division, which would result in <code>1/3</code> returning the floor <code>0</code> instead of <code>0.3333333333333333</code>.  The second line tells Python to import everything from the visual (VPython) library for you to use.
<code>v = vec(3, 0, -2)</code>


After these two lines, you can create objects, assign variables, do calculations, and much more.  You can also run VPython from the command line, although it may require additional setup so Python can locate the <code>visual</code> module.
Vectors support the operations you would expect:


===Glowscript===
{| class="wikitable"
|-
! Operation !! Syntax !! Returns
|-
| Magnitude || <code>mag(v)</code> || scalar
|-
| Magnitude squared || <code>mag2(v)</code> || scalar
|-
| Unit vector || <code>hat(v)</code> || vector
|-
| Dot product || <code>dot(a, b)</code> || scalar
|-
| Cross product || <code>cross(a, b)</code> || vector
|-
| Component access || <code>v.x</code>, <code>v.y</code>, <code>v.z</code> || scalar
|}


Another useful method of using Vpython can be found at http://www.glowscript.org/. At this website, a user can make an account and have a script up and running within minutes on a web browser without having to deal with downloading any software or worrying about compatibility. Only downside is that it can be tricky to save the code for submitting to Webassign.
You can add and subtract vectors with <code>+</code> and <code>-</code>, and multiply or divide by a scalar with <code>*</code> and <code>/</code>. You ''cannot'' multiply two vectors with <code>*</code> — use <code>dot</code> or <code>cross</code> instead. Forgetting this is the single most common bug for new users.


==Creating VPython Objects==
==Creating Objects==
When you create objects, it is often useful to assign them to variables so you can reference them later to either get or set values describing for example the position and size of the object.


'''Sphere'''
Every VPython object takes <code>pos</code> as a vector and most take a <code>color</code>. The center-vs-end convention is worth memorizing because it trips people up:


<code>particle = sphere(pos=(0,0,0), radius=4, color=color.blue)</code>
{| class="wikitable"
|-
! Object !! <code>pos</code> refers to !! Other key parameters
|-
| <code>sphere</code> || center || <code>radius</code>
|-
| <code>box</code> || center || <code>size</code> (a vector)
|-
| <code>ring</code> || center || <code>radius</code>, <code>thickness</code>, <code>axis</code>
|-
| <code>arrow</code> || tail end || <code>axis</code> (vector from tail to head)
|-
| <code>cylinder</code> || one end || <code>axis</code>, <code>radius</code>
|-
| <code>helix</code> || one end || <code>axis</code>, <code>radius</code>, <code>coils</code>
|-
| <code>pyramid</code> || base center || <code>size</code>
|}


This creates a blue sphere centered at the origin <0,0,0> with radius 4.
A few examples:


'''Arrow'''
<nowiki>
particle = sphere(pos=vector(0,0,0), radius=0.4, color=color.blue, make_trail=True)


<code>arrowToOrigin = arrow(pos=(0,2,0), axis=(0,8,0), color=color.green)</code>
field_arrow = arrow(pos=vector(0,2,0), axis=vector(0,8,0), color=color.green)


This creates a green arrow pointing from <0,2,0> to <0,10,0>.  Note that <code>axis</code> is always relative to the start of the arrow, not the origin <0,0,0>.
wire = cylinder(pos=vector(0,0,0), axis=vector(20,0,0), radius=0.1, color=color.yellow)


'''Cylinder'''
spring = helix(pos=vector(0,0,0), axis=vector(10,0,0), radius=0.75, color=color.cyan, coils=15, thickness=0.1)


<code>wire = cylinder(pos=(0,0,0), axis=(20,0,0), radius=1, color=color.yellow)</code>
table = box(pos=vector(0,-1,0), size=vector(20,0.2,10), color=color.white)
</nowiki>


This creates a yellow cylinder starting at the origin <0,0,0> and extending to <20,0,0> with radius 1.
The <code>make_trail=True</code> argument on the sphere is worth knowing: VPython will then draw a curve following the object as you move it, which is invaluable for visualizing trajectories.


'''Helix'''
==Updating Objects==


<code>spring = helix(pos=(0,0,0), axis=(10,0,0), radius=0.75, color=color.cyan)</code>
Once you have assigned an object to a variable, you change it by reassigning attributes:


Creates a helix of color cyan at the origin and goes to <10,0,0> with a radius of 0.75.
<nowiki>
particle.pos = vector(-5,-5,0)              # teleport
particle.pos = particle.pos + vec(1,0,0)    # nudge by +x
field_arrow.axis = vector(-10, 5, 0)
wire.radius = 3
particle.color = color.red
</nowiki>


'''Pyramid'''
This is the entire mechanism behind VPython animation: you change <code>pos</code> in a loop, and the screen redraws.


<code>shape = pyramid(pos=(8,4,0), size=(20,4,10), color=color.red)</code>
==The Animation Loop: Iterative Prediction==


Creates a pyramid of size <20,4,10> starting at <8,4,0>
This is the pattern that virtually every physics simulation in this course follows.


'''Object Positioning'''
<nowiki>
from vpython import *


It is very important to note that the position values for arrow, cylinder, helix, and pyramid corresponds to one end of the object, however for a box, sphere, or ring it corresponds to the center of the object.
# 1. Set up the scene
ball = sphere(pos=vector(-10, 0, 0), radius=0.5, color=color.cyan, make_trail=True)
g = vector(0, -9.8, 0)              # gravitational field
ball.m = 0.1                        # mass in kg
ball.p = ball.m * vector(15, 20, 0)  # initial momentum


'''Example'''
# 2. Set up time
[[File:VPythonObjects.png|thumb|Result of example code]]
t = 0
<nowiki>
dt = 0.01
from __future__ import division
from visual import *


particle = sphere(pos=(0,0,0), radius=4, color=color.blue)
# 3. Iterate
arrowToOrigin = arrow(pos=(0,2,0), axis=(0,8,0), color=color.green)
while ball.pos.y > -10:
wire = cylinder(pos=(0,0,0), axis=(20,0,0), radius=1, color=color.yellow)</nowiki>
    rate(200)                                       # cap at 200 frames/sec
    F_net = ball.m * g                              # net force
    ball.p = ball.p + F_net * dt                    # momentum update (Newton's 2nd law)
    ball.pos = ball.pos + (ball.p / ball.m) * dt    # position update
    t = t + dt
</nowiki>


'''Updating objects'''
A few things to notice. The <code>rate(200)</code> call is what keeps the animation watchable — without it, the loop runs as fast as your CPU allows, and the ball appears to teleport. The momentum form of Newton's second law (<code>p = p + F*dt</code>) is preferred over the velocity form because it generalizes to relativistic problems later in PHYS 2212. And the trail on the sphere makes the parabola visible without any extra plotting code.
If you assign an object to a variable (such as <code>particle</code> or <code>arrowToOrigin</code> above) you can adjust its parameters such as its location. For the above sphere, you can change its location to <-5,-5,0> with:


<code>particle.pos=(-5,-5,0)</code>
===Embedded example: projectile motion===


To change the axis of the above arrow to point to <-10,5,0>, use:
<iframe src="https://trinket.io/embed/glowscript/31d0f9ad9e" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>


<code>arrowToOrigin.axis=(-10,5,0)</code>
''Press the play button to run the simulation.''


To change the radius of the above cylinder to 3, use:
==Worked Example: Spring–Mass Oscillator==


<code>wire.radius=3</code>
The classic first oscillation problem: a mass on a horizontal spring with no friction. The spring force is <code>F = -k * s</code>, where <code>s</code> is the displacement from the relaxed length.


'''Example'''
<nowiki>
[[File:VPythonObjectsChanged.png|thumb|Result of example code]]
from vpython import *
<nowiki>
from __future__ import division
from visual import *


particle = sphere(pos=(0,0,0), radius=4, color=color.blue)
# Constants
arrowToOrigin = arrow(pos=(0,2,0), axis=(0,8,0), color=color.green)
k = 12        # spring constant (N/m)
wire = cylinder(pos=(0,0,0), axis=(20,0,0), radius=1, color=color.yellow)
L0 = 1.0       # relaxed length (m)
m = 0.2        # mass (kg)


particle.pos=(-5,-5,0)
# Objects
arrowToOrigin.axis=(-10,5,0)
wall = box(pos=vector(-1.2, 0, 0), size=vector(0.05, 1, 1), color=color.gray(0.5))
wire.radius=3</nowiki>
ball = sphere(pos=vector(0.5, 0, 0), radius=0.08, color=color.orange, make_trail=True)
spring = helix(pos=wall.pos, axis=ball.pos - wall.pos, radius=0.05,
              coils=20, thickness=0.01, color=color.cyan)


==Useful built-in functions==
ball.m = m
ball.p = vector(0, 0, 0)  # released from rest


VPython includes various functions that can make your calculations much easier.  The following functions simplify mathematical operations on vectors and will come in handy very often.
t = 0
dt = 0.001


'''Cross-multiply two vectors'''
while t < 10:
    rate(1000)
    L = ball.pos - wall.pos
    s = mag(L) - L0
    F_spring = -k * s * hat(L)
    ball.p = ball.p + F_spring * dt
    ball.pos = ball.pos + ball.p / ball.m * dt
    spring.axis = ball.pos - wall.pos
    t = t + dt
</nowiki>


<code>cross(vectorA, vectorB)</code>
Notice how <code>spring.axis</code> is updated each step so the helix visibly stretches and compresses with the mass. This is a small but important habit: any geometric object connecting two moving things needs its <code>axis</code> (or <code>pos</code>) updated inside the loop.


'''Magnitude of a vector'''
<iframe src="https://trinket.io/embed/glowscript/31d0f9ad9e" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>


<code>mag(vector)</code>
==Worked Example: Orbit Around a Planet==


'''Square of the Magnitude of a vector'''
Gravity scales as <code>1/r²</code>, so the force calculation is slightly more involved.


<code>mag2(vector)</code>
<nowiki>
from vpython import *


'''Unit vector of a vector'''
G = 6.7e-11
M_earth = 6e24


<code>norm(vector)</code>
earth = sphere(pos=vector(0,0,0), radius=6.4e6, color=color.blue)
craft = sphere(pos=vector(0, 7e6, 0), radius=2e5, color=color.white, make_trail=True)
craft.m = 1500
craft.p = craft.m * vector(7800, 0, 0)   # roughly low-Earth-orbit speed


'''Square Root'''
t = 0
dt = 1  # 1-second steps


<code>sqrt(value)</code>
while t < 6000:
    rate(1000)
    r = craft.pos - earth.pos
    F_grav = -G * M_earth * craft.m / mag2(r) * hat(r)
    craft.p = craft.p + F_grav * dt
    craft.pos = craft.pos + craft.p / craft.m * dt
    t = t + dt
</nowiki>


'''Absolute Value'''
If the initial speed is too small, the craft spirals in and crashes; too large, and it escapes. Tuning the initial momentum until the orbit closes on itself is one of the more satisfying ways to internalize what "circular orbital speed" actually means.


<code>abs(value)</code>
<iframe src="https://trinket.io/embed/glowscript/31d0f9ad9e" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>


==VPython Operators==
==Common Pitfalls==


===Mathematical Operators===
* '''Mixing tuples and vectors.''' <code>pos=(0,0,0)</code> worked in older Classic VPython but not in modern GlowScript. Always use <code>vector(0,0,0)</code> or <code>vec(0,0,0)</code>.
1) #  comment out a line
* '''Forgetting <code>rate()</code>.''' Without it, your loop runs at full CPU speed and the simulation appears to skip directly to the end.
* '''Multiplying two vectors with <code>*</code>.''' This raises an error. You meant <code>dot</code> or <code>cross</code>.
* '''Updating <code>pos</code> before momentum.''' Either order is mathematically fine for small <code>dt</code>, but the standard convention in this course is momentum first, then position — keep it consistent so your code reads cleanly.
* '''Wrong <code>dt</code>.''' Stiff systems (large spring constants, close orbits) need very small time steps. If your simulation explodes outward, try <code>dt</code> ten times smaller before suspecting a code bug.


2) + - * /  addition, subtraction, multiplication, division
==Other Useful Built-in Functions==


3) ** exponential
Beyond the vector functions in the table above, you will see these constantly:


4) % modulus or remainder
{| class="wikitable"
|-
! Function !! Purpose
|-
| <code>rate(N)</code> || cap loop at N iterations per second
|-
| <code>sleep(t)</code> || pause the program for ''t'' seconds
|-
| <code>graph()</code>, <code>gcurve()</code> || open a 2D plot window for energy, position, etc.
|-
| <code>scene.camera.follow(obj)</code> || keep the camera centered on a moving object
|-
| <code>scene.background</code> || set the background color
|-
| <code>sqrt(x)</code>, <code>sin(x)</code>, <code>cos(x)</code>, <code>atan2(y,x)</code> || standard math
|-
| <code>pi</code> || the constant π
|}


===Logical Operators===
==Operators==
1) ==  outputs true if the compared values are the same


2) != outputs true if the compared values are not the same
===Mathematical===
{| class="wikitable"
|-
! Operator !! Meaning
|-
| <code>#</code> || comment out the rest of a line
|-
| <code>+ - * /</code> || addition, subtraction, multiplication, division
|-
| <code>**</code> || exponentiation (e.g. <code>r**2</code>)
|-
| <code>%</code> || modulus (remainder)
|-
| <code>//</code> || integer division
|}


3) > or < outputs true if the compared values are greater or less than the other
===Comparison===
 
{| class="wikitable"
4) >= or <= Same as above but outputs true if greater or less than or equal to the compared value
|-
! Operator !! Meaning
|-
| <code>==</code> || equal
|-
| <code>!=</code> || not equal
|-
| <code><</code>, <code>></code> || strictly less / greater
|-
| <code><=</code>, <code>>=</code> || less or equal / greater or equal
|}


==Connectedness==
==Connectedness==


I am very interested in programming. I have used Python for years, so translating Physics problems into VPython code is a great way to cement the fundamental ideas in my mind.
The reason VPython works as a teaching tool is that it collapses the gap between the equation on the page and the thing the equation describes. Writing <code>p = p + F*dt</code> in a loop and watching a ball trace a parabola is a different kind of understanding than solving for the range algebraically — you can ''feel'' that the motion is just two scalar updates repeated very quickly. That is the same pattern that scales up to game engines, molecular dynamics, and orbital mechanics in industry, so the habit is worth building early.


VPython is a great tool to bridge the worlds of Computer Science and Physics.  Many of the calculations required to model a physical object would be tedious if done by hand.  Yet with often a few lines of code, this work can be reduced to almost nothing.
VPython itself is most often used in physics education, but the underlying numerical-integration pattern is everywhere. NASA has published a few VPython models for atmospheric and gravitational systems, and research groups occasionally use it for prototyping before moving to a faster language.
 
NASA has published [http://gcmd.gsfc.nasa.gov/KeywordSearch/Metadata.do?Portal=GCMD&MetadataType=1&MetadataView=Full&KeywordPath=&EntryId=3-D_ES-Models VPython models].  However, VPython is still primarily used in an educational context.


==History==
==History==


VPython was originally released in 2000 by David Scherer after he took an introductory physics class at Carnegie Mellon University.  At the time, the school used the cT programming language for 2D modeling, and David saw the need for something better. Working with several people including professors Ruth Chabay and Bruce Sherwood, he developed a Python module called Visual. Visual Python or VPython featured 3D modeling, as well as an easier-to-understand object-oriented syntax.  Beginning in 2002, the National Science Foundation had awarded $292,286.00 as of December 2015 for the further development of this tool.  VPython is released under an Open Source license, and development continues today.
VPython was released in 2000 by David Scherer, then a student at Carnegie Mellon, who built it after taking an introductory physics course taught with the older 2D ''cT'' language. He worked with Ruth Chabay and Bruce Sherwood — the authors of ''Matter and Interactions'', the textbook used in PHYS 2211/2212 — to develop the module further. The National Science Foundation funded continued development, and VPython has been rewritten twice since then: once around 2014 to use a wxPython-based renderer (the "Classic VPython 6" that earlier versions of this page described), and again with GlowScript, which moved everything into the browser using WebGL and JavaScript. The Python-on-the-desktop version was rebuilt on top of the GlowScript renderer so that both environments share the same visual library.


== See also ==
==See also==


If you have never used Python, the [[VPython_basics| VPython Basics]] wiki page has information for getting started with Python programming.
* [[VPython_basics|VPython Basics]] for readers brand new to Python
 
* [[Iterative_Prediction|Iterative Prediction]] — the conceptual underpinning of every animation loop above
===Further reading===
* [[Vectors|Vectors]] — the math you should know cold before reading much further
 
Aiken, John M (2013). ''Transforming High School Physics With Modeling And Computation''. Georgia State University.


===External links===
===External links===


[http://www.wired.com/2015/08/coding-physics-course/ You Should Be Coding in Your Physics Course]
* [https://www.glowscript.org/ GlowScript] — run VPython in your browser
 
* [https://www.vpython.org/ vpython.org] — official documentation for the desktop version
[http://vpython.wikidot.com/ VPython Wiki Site]
* [https://trinket.io/glowscript Trinket GlowScript] — embed VPython programs in webpages
 
* [https://groups.google.com/forum/#!forum/vpython-users VPython user group]
[https://groups.google.com/forum/#!forum/vpython-users VPython user group]


==References==
==References==


This section contains the the references you used while writing this page
* Chabay, R. & Sherwood, B. ''Matter and Interactions'', 4th ed. Wiley, 2015.
 
* Scherer, D., Dubois, P., & Sherwood, B. (2000). ''VPython: 3D Interactive Scientific Graphics for Students''. Computing in Science and Engineering.
[http://vpython.org/contents/cTsource/cToverview.html The cT Programming Language]
* [https://www.vpython.org/ VPython official documentation]
 
* [https://www.glowscript.org/docs/VPythonDocs/index.html GlowScript VPython documentation]
[https://wiki.python.org/moin/VPython/ VPython - Python Wiki]
* Aiken, J.M. (2013). ''Transforming High School Physics With Modeling And Computation''. Georgia State University.
 
[http://www.nsf.gov/awardsearch/showAward?AWD_ID=0237132 VPython NSF Award]


[[Category:VPython]]
[[Category:VPython]]

Latest revision as of 00:05, 29 April 2026

Page edited by Caio — Spring 2026

VPython is a Python module that turns a few lines of code into a real-time, three-dimensional animation. It was built specifically for physics teaching: instead of solving differential equations on paper, you write a short loop that takes a small time step, applies Newton's second law, and watches the result move. This is the same iterative prediction strategy used throughout the Matter and Interactions curriculum (PHYS 2211/2212), which is why this course leans on VPython so heavily.

Error creating thumbnail: sh: /usr/bin/convert: No such file or directory Error code: 127
VPython animating the magnetic force on a moving charged particle

Two Ways to Run VPython

You have two reasonable options. New users should almost always start with GlowScript.

GlowScript (recommended for this course)

GlowScript is VPython in your browser. There is nothing to install; you sign in with a Google account, write your program in the online editor, and the simulation renders in the same page. This is also what Trinket uses behind the scenes when you embed simulations on a webpage like this one.

A GlowScript program begins with:

GlowScript 3.2 VPython

That header is added automatically when you create a new program; you do not type it yourself.

Local install with Python 3

If you prefer to run VPython on your own machine — for example, because you want to integrate it with NumPy, Pandas, or a Jupyter notebook — install it with pip:

pip install vpython

This works on Windows, macOS, and Linux as long as you have Python 3.7 or newer. Anaconda users can instead run:

conda install -c vpython vpython

The local install opens its own browser tab to display the 3D scene; the Python program drives the simulation, and the browser is just the renderer.

Note: older versions of this page described installing Classic VPython 6 alongside Python 2.7. That version has been deprecated since 2020 and is no longer maintained. The instructions above replace it.

Vectors: the One Concept That Matters Most

Almost every physics quantity in VPython is a vector — position, velocity, momentum, force, magnetic field. You construct a vector with:

v = vector(3, 0, -2)

or, for short:

v = vec(3, 0, -2)

Vectors support the operations you would expect:

Operation Syntax Returns
Magnitude mag(v) scalar
Magnitude squared mag2(v) scalar
Unit vector hat(v) vector
Dot product dot(a, b) scalar
Cross product cross(a, b) vector
Component access v.x, v.y, v.z scalar

You can add and subtract vectors with + and -, and multiply or divide by a scalar with * and /. You cannot multiply two vectors with * — use dot or cross instead. Forgetting this is the single most common bug for new users.

Creating Objects

Every VPython object takes pos as a vector and most take a color. The center-vs-end convention is worth memorizing because it trips people up:

Object pos refers to Other key parameters
sphere center radius
box center size (a vector)
ring center radius, thickness, axis
arrow tail end axis (vector from tail to head)
cylinder one end axis, radius
helix one end axis, radius, coils
pyramid base center size

A few examples:

particle = sphere(pos=vector(0,0,0), radius=0.4, color=color.blue, make_trail=True) field_arrow = arrow(pos=vector(0,2,0), axis=vector(0,8,0), color=color.green) wire = cylinder(pos=vector(0,0,0), axis=vector(20,0,0), radius=0.1, color=color.yellow) spring = helix(pos=vector(0,0,0), axis=vector(10,0,0), radius=0.75, color=color.cyan, coils=15, thickness=0.1) table = box(pos=vector(0,-1,0), size=vector(20,0.2,10), color=color.white)

The make_trail=True argument on the sphere is worth knowing: VPython will then draw a curve following the object as you move it, which is invaluable for visualizing trajectories.

Updating Objects

Once you have assigned an object to a variable, you change it by reassigning attributes:

particle.pos = vector(-5,-5,0) # teleport particle.pos = particle.pos + vec(1,0,0) # nudge by +x field_arrow.axis = vector(-10, 5, 0) wire.radius = 3 particle.color = color.red

This is the entire mechanism behind VPython animation: you change pos in a loop, and the screen redraws.

The Animation Loop: Iterative Prediction

This is the pattern that virtually every physics simulation in this course follows.

from vpython import * # 1. Set up the scene ball = sphere(pos=vector(-10, 0, 0), radius=0.5, color=color.cyan, make_trail=True) g = vector(0, -9.8, 0) # gravitational field ball.m = 0.1 # mass in kg ball.p = ball.m * vector(15, 20, 0) # initial momentum # 2. Set up time t = 0 dt = 0.01 # 3. Iterate while ball.pos.y > -10: rate(200) # cap at 200 frames/sec F_net = ball.m * g # net force ball.p = ball.p + F_net * dt # momentum update (Newton's 2nd law) ball.pos = ball.pos + (ball.p / ball.m) * dt # position update t = t + dt

A few things to notice. The rate(200) call is what keeps the animation watchable — without it, the loop runs as fast as your CPU allows, and the ball appears to teleport. The momentum form of Newton's second law (p = p + F*dt) is preferred over the velocity form because it generalizes to relativistic problems later in PHYS 2212. And the trail on the sphere makes the parabola visible without any extra plotting code.

Embedded example: projectile motion

<iframe src="https://trinket.io/embed/glowscript/31d0f9ad9e" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

Press the play button to run the simulation.

Worked Example: Spring–Mass Oscillator

The classic first oscillation problem: a mass on a horizontal spring with no friction. The spring force is F = -k * s, where s is the displacement from the relaxed length.

from vpython import * # Constants k = 12 # spring constant (N/m) L0 = 1.0 # relaxed length (m) m = 0.2 # mass (kg) # Objects wall = box(pos=vector(-1.2, 0, 0), size=vector(0.05, 1, 1), color=color.gray(0.5)) ball = sphere(pos=vector(0.5, 0, 0), radius=0.08, color=color.orange, make_trail=True) spring = helix(pos=wall.pos, axis=ball.pos - wall.pos, radius=0.05, coils=20, thickness=0.01, color=color.cyan) ball.m = m ball.p = vector(0, 0, 0) # released from rest t = 0 dt = 0.001 while t < 10: rate(1000) L = ball.pos - wall.pos s = mag(L) - L0 F_spring = -k * s * hat(L) ball.p = ball.p + F_spring * dt ball.pos = ball.pos + ball.p / ball.m * dt spring.axis = ball.pos - wall.pos t = t + dt

Notice how spring.axis is updated each step so the helix visibly stretches and compresses with the mass. This is a small but important habit: any geometric object connecting two moving things needs its axis (or pos) updated inside the loop.

<iframe src="https://trinket.io/embed/glowscript/31d0f9ad9e" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

Worked Example: Orbit Around a Planet

Gravity scales as 1/r², so the force calculation is slightly more involved.

from vpython import * G = 6.7e-11 M_earth = 6e24 earth = sphere(pos=vector(0,0,0), radius=6.4e6, color=color.blue) craft = sphere(pos=vector(0, 7e6, 0), radius=2e5, color=color.white, make_trail=True) craft.m = 1500 craft.p = craft.m * vector(7800, 0, 0) # roughly low-Earth-orbit speed t = 0 dt = 1 # 1-second steps while t < 6000: rate(1000) r = craft.pos - earth.pos F_grav = -G * M_earth * craft.m / mag2(r) * hat(r) craft.p = craft.p + F_grav * dt craft.pos = craft.pos + craft.p / craft.m * dt t = t + dt

If the initial speed is too small, the craft spirals in and crashes; too large, and it escapes. Tuning the initial momentum until the orbit closes on itself is one of the more satisfying ways to internalize what "circular orbital speed" actually means.

<iframe src="https://trinket.io/embed/glowscript/31d0f9ad9e" width="100%" height="600" frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>

Common Pitfalls

  • Mixing tuples and vectors. pos=(0,0,0) worked in older Classic VPython but not in modern GlowScript. Always use vector(0,0,0) or vec(0,0,0).
  • Forgetting rate(). Without it, your loop runs at full CPU speed and the simulation appears to skip directly to the end.
  • Multiplying two vectors with *. This raises an error. You meant dot or cross.
  • Updating pos before momentum. Either order is mathematically fine for small dt, but the standard convention in this course is momentum first, then position — keep it consistent so your code reads cleanly.
  • Wrong dt. Stiff systems (large spring constants, close orbits) need very small time steps. If your simulation explodes outward, try dt ten times smaller before suspecting a code bug.

Other Useful Built-in Functions

Beyond the vector functions in the table above, you will see these constantly:

Function Purpose
rate(N) cap loop at N iterations per second
sleep(t) pause the program for t seconds
graph(), gcurve() open a 2D plot window for energy, position, etc.
scene.camera.follow(obj) keep the camera centered on a moving object
scene.background set the background color
sqrt(x), sin(x), cos(x), atan2(y,x) standard math
pi the constant π

Operators

Mathematical

Operator Meaning
# comment out the rest of a line
+ - * / addition, subtraction, multiplication, division
** exponentiation (e.g. r**2)
% modulus (remainder)
// integer division

Comparison

Operator Meaning
== equal
!= not equal
<, > strictly less / greater
<=, >= less or equal / greater or equal

Connectedness

The reason VPython works as a teaching tool is that it collapses the gap between the equation on the page and the thing the equation describes. Writing p = p + F*dt in a loop and watching a ball trace a parabola is a different kind of understanding than solving for the range algebraically — you can feel that the motion is just two scalar updates repeated very quickly. That is the same pattern that scales up to game engines, molecular dynamics, and orbital mechanics in industry, so the habit is worth building early.

VPython itself is most often used in physics education, but the underlying numerical-integration pattern is everywhere. NASA has published a few VPython models for atmospheric and gravitational systems, and research groups occasionally use it for prototyping before moving to a faster language.

History

VPython was released in 2000 by David Scherer, then a student at Carnegie Mellon, who built it after taking an introductory physics course taught with the older 2D cT language. He worked with Ruth Chabay and Bruce Sherwood — the authors of Matter and Interactions, the textbook used in PHYS 2211/2212 — to develop the module further. The National Science Foundation funded continued development, and VPython has been rewritten twice since then: once around 2014 to use a wxPython-based renderer (the "Classic VPython 6" that earlier versions of this page described), and again with GlowScript, which moved everything into the browser using WebGL and JavaScript. The Python-on-the-desktop version was rebuilt on top of the GlowScript renderer so that both environments share the same visual library.

See also

External links

References

  • Chabay, R. & Sherwood, B. Matter and Interactions, 4th ed. Wiley, 2015.
  • Scherer, D., Dubois, P., & Sherwood, B. (2000). VPython: 3D Interactive Scientific Graphics for Students. Computing in Science and Engineering.
  • VPython official documentation
  • GlowScript VPython documentation
  • Aiken, J.M. (2013). Transforming High School Physics With Modeling And Computation. Georgia State University.