VPython: Difference between revisions

From Physics Book
Jump to navigation Jump to search
Ncheek (talk | contribs)
Populated objects section
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.
 
(44 intermediate revisions by 8 users not shown)
Line 1: Line 1:
Claimed by Nathan Cheek
'''<span style="font-size: 150%">Page edited by Caio — Spring 2026</span>'''


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.
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.


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


==Installation==
==Two Ways to Run VPython==


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.
You have two reasonable options. New users should almost always start with GlowScript.


===Windows===
===GlowScript (recommended for this course)===
[[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].
[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.


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].
A GlowScript program begins with:


<code>GlowScript 3.2 VPython</code>


To troubleshoot any installation issues, look at the extensive [http://vpython.org/contents/download_windows.html VPython Windows installation guide].
That header is added automatically when you create a new program; you do not type it yourself.


===OSX===
===Local install with Python 3===
[[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.
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:


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].
<code>pip install vpython</code>


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


To troubleshoot installation issues, see the extensive [http://vpython.org/contents/download_mac.html VPython Mac installation guide].
<code>conda install -c vpython vpython</code>


===GNU/Linux===
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.
[[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:
''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.''


<code>sudo apt-get install python-visual</code>
==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:


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.
<code>v = vector(3, 0, -2)</code>


==Getting started with VPython==
or, for short:
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>
<code>v = vec(3, 0, -2)</code>


This 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>.
Vectors support the operations you would expect:


<code>from visual import *</code>
{| 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
|}


This line tells Python to import everything from the visual (VPython) library for you to use.
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.


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.
==Creating Objects==


==Creating VPython Objects==
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:
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 such as the position and size of the object.


'''Sphere'''
{| 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>
|}


<code>particle = sphere(pos=(0,0,0), radius=8, color=color.blue)</code>
A few examples:


This creates a blue sphere at the origin with radius 8.
<nowiki>
particle = sphere(pos=vector(0,0,0), radius=0.4, color=color.blue, make_trail=True)


'''Arrow'''
field_arrow = arrow(pos=vector(0,2,0), axis=vector(0,8,0), color=color.green)


<code>arrowToOrigin = arrow(pos=(5,0,0), axis=(-5,0,0), color=color.green)</code>
wire = cylinder(pos=vector(0,0,0), axis=vector(20,0,0), radius=0.1, color=color.yellow)


This creates a green arrow pointing from <5,0,0> to the origin <0,0,0>.
spring = helix(pos=vector(0,0,0), axis=vector(10,0,0), radius=0.75, color=color.cyan, coils=15, thickness=0.1)


'''Cylinder'''
table = box(pos=vector(0,-1,0), size=vector(20,0.2,10), color=color.white)
</nowiki>


<code>wire = cylinder(pos=(0,0,0), axis=(100,0,0), radius=1, color=color.yellow)</code>
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.


'''Updating objects'''
==Updating Objects==


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 <1,2,3> with:
Once you have assigned an object to a variable, you change it by reassigning attributes:


<code>particle.pos=(1,2,3)</code>
<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>


To change the axis of the above arrow to point to <5,0,10>, use:
This is the entire mechanism behind VPython animation: you change <code>pos</code> in a loop, and the screen redraws.


<code>arrowToOrigin.axis=(0,0,10)</code>
==The Animation Loop: Iterative Prediction==


==Useful built-in functions==
This is the pattern that virtually every physics simulation in this course follows.


===Vectors===
<nowiki>
#cross(vectorA, vectorB)
from vpython import *
#mag(vector)


==Connectedness==
# 1. Set up the scene
#How is this topic connected to something that you are interested in?
ball = sphere(pos=vector(-10, 0, 0), radius=0.5, color=color.cyan, make_trail=True)
#How is it connected to your major?
g = vector(0, -9.8, 0)              # gravitational field
#Is there an interesting industrial application?
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
</nowiki>
 
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.
 
===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 <code>F = -k * s</code>, where <code>s</code> is the displacement from the relaxed length.
 
<nowiki>
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
</nowiki>
 
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.
 
<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 <code>1/r²</code>, so the force calculation is slightly more involved.
 
<nowiki>
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
</nowiki>
 
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.''' <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>.
* '''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.
 
==Other Useful Built-in Functions==
 
Beyond the vector functions in the table above, you will see these constantly:


==History==
{| 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 π
|}


Put this idea in historical context. Give the reader the Who, What, When, Where, and Why.
==Operators==


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.  VPython is released under an Open Source license, and development continues today.
===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
|}


== See also ==
===Comparison===
{| class="wikitable"
|-
! 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
|}


Are there related topics or categories in this wiki resource for the curious reader to explore?  How does this topic fit into that context?
==Connectedness==


See the [[VPython_basics| VPython Basics]] wiki page for getting started with Python programming.
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.


===Further reading===
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.


Books, Articles or other print media on this topic
==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==
 
* [[VPython_basics|VPython Basics]] — for readers brand new to Python
* [[Iterative_Prediction|Iterative Prediction]] — the conceptual underpinning of every animation loop above
* [[Vectors|Vectors]] — the math you should know cold before reading much further


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


Internet resources on this topic
* [https://www.glowscript.org/ GlowScript] — run VPython in your browser
* [https://www.vpython.org/ vpython.org] — official documentation for the desktop version
* [https://trinket.io/glowscript Trinket GlowScript] — embed VPython programs in webpages
* [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.
1. [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]
2. [http://vpython.wikidot.com/ VPython Wiki Site]
* Aiken, J.M. (2013). ''Transforming High School Physics With Modeling And Computation''. Georgia State University.


[[Category:Which Category did you place this in?]]
[[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.