VPython

From Physics Book
Revision as of 00:05, 29 April 2026 by 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.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

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.