VPython: Difference between revisions

From Physics Book
Jump to navigation Jump to search
No edit summary
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.
 
(64 intermediate revisions by 10 users not shown)
Line 1: Line 1:
Claimed by Liubov Nikolenko
'''<span style="font-size: 150%">Page edited by Caio — Spring 2026</span>'''


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.


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.
[[File:VPythonMagneticForceAnimated.gif|thumb|VPython animating the magnetic force on a moving charged particle]]


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


To install VPython simply follow the instructions in the links given below.  
You have two reasonable options. New users should almost always start with GlowScript.


===Windows===
===GlowScript (recommended for this course)===
Install VPython [http://vpython.org/contents/download_windows.html here]


===OSX===
[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.


Install VPython [http://vpython.org/contents/download_mac.html here]
A GlowScript program begins with:


===Linux===
<code>GlowScript 3.2 VPython</code>


Install VPython [http://vpython.org/contents/download_linux.html here]
That header is added automatically when you create a new program; you do not type it yourself.


==Getting started with Python==
===Local install with Python 3===
Introduction to basic Python use
 
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>
 
This works on Windows, macOS, and Linux as long as you have Python 3.7 or newer. Anaconda users can instead run:
 
<code>conda install -c vpython vpython</code>
 
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:
 
<code>v = vector(3, 0, -2)</code>
 
or, for short:
 
<code>v = vec(3, 0, -2)</code>
 
Vectors support the operations you would expect:
 
{| 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
|}
 
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 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:
 
{| 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>
|}
 
A few examples:
 
<nowiki>
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)
</nowiki>
 
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==
 
Once you have assigned an object to a variable, you change it by reassigning attributes:
 
<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>
 
This is the entire mechanism behind VPython animation: you change <code>pos</code> 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.
 
<nowiki>
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
</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:
 
{| 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 π
|}
 
==Operators==
 
===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
|}
 
===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
|}


===Creating VPython Objects===
*Sphere
ball = sphere(pos=(x_coordinate,y_coordinate,z_coordinate), radius=radius_of_the_sphere, color = color.color_of_the_sphere)
*Arrow
myArrow = arrow(pos=(x0_coordinate,y0_coordinate,z0_coordinate), axis=(x1_coordinate,y1_coordinate,z1_coordinate), color = color.color_of_the_arrow)
*Vector
myVector = vector(x_coordinate,y_coordinate,z_coordinate)
===Manipulating VPython values===
*Accessing attributes of the object
To access the attribute of a given object just use the syntax ''object.attribute'' (e.g. to access the position of the ball object, you should do ball.pos)
*Updating values
To update a value (such as time, speed, force or the position of the object) you should do ''value = value + delta_value''
===Running VPython code===
To run VPython code simply press F5. While running your code you will see the visual module and a shell(a place where all print out information is displayed)
===Loops===
There are two types of loops that can be use in Python: [https://wiki.python.org/moin/ForLoop for loop] and [https://wiki.python.org/moin/WhileLoop while loop]. Basically, loops are used to tell the computer to execute the same task multiple times. While loops are more common for modeling physics concepts.
*While loops
The body of a while loop is executed, while a certain condition is true. Make sure to indent the statements that should be done in the while loop. While loop has the following structure:
:while(condition)
::the body of the while loop
::updating the loop
For example:
:while(t < 60)
::distance = distance + velocity * deltat
::t = t + deltat
===Debugging techniques===
Unfortunately, sometimes programs do not work in a way we intended them to work. Here are some tips to fixing your code.
#If you get an error try to understand the error message and fix your code accordingly. The most common errors are syntax errors, like parenthesis mismatch or wrong arguments in the function.
#Make sure you updating your condition for a while loop, so you don't have an infinite loop.
#Check if your are dividing by zero anywhere.
#Put plenty of ''print()'' statements, so you can know what is going on in every single stage of your code.
 
===Useful built-in functions===
====Printing out information====
*print(value)
Prints put the given value in the programming shell.
====Math====
*x**y
Raises x to the y-th power.
===Vectors===
*cross(vectorA, vectorB)
Calculates the cross product of two vectors
*mag(vector)
Calculates the magnitude of the vector
*norm(vector)
Calculates the unit vector of the vector
==Connectedness==
==Connectedness==
#How is this topic connected to something that you are interested in?
 
I like coding and I would love more people to share my passion, so I tried my best to make the coding part of physics more approachable
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.
#How is it connected to your major?
 
I am CS major and Python was the first language I have learned at Tech.  
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.
#Is there an interesting industrial application?
Every simulation starting from interaction of molecules can be modeled in VPython to get the general idea of the process.  


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


== See also ==
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.
===GlowScript====
 
[http://www.glowscript.org/ GlowScript] is an easy-to-use, powerful environment for creating 3D animations and publishing them on the web. You can write and run GlowScript programs right in your browser, store them in the cloud for free, and easily share them with others. GlowScript uses VPython as a programming language.
==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===
[http://vpython.org/contents/doc.html Documentation]
[https://groups.google.com/forum/?fromgroups&hl=en#!forum/vpython-users User forum]
==References==


This section contains the the references you used while writing this page
* [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]


1. [http://vpython.org/contents/cTsource/cToverview.html The cT Programming Language]
==References==
 
2. [http://vpython.wikidot.com/ VPython Wiki Site]


3. [http://www.glowscript.org/ GlowScript]
* 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.
* [https://www.vpython.org/ VPython official documentation]
* [https://www.glowscript.org/docs/VPythonDocs/index.html GlowScript VPython documentation]
* 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.