VPython Loops: Difference between revisions

From Physics Book
Jump to navigation Jump to search
(Undo revision 22435 by Csyed3 (talk))
No edit summary
 
(25 intermediate revisions by 3 users not shown)
Line 1: Line 1:
Claimed by Alyx Falis
An introduction to creating and using loops in VPython.


What loops are and how to use them in a VPython Program
==The Main Idea==
The most commonly used loop structures in VPython are the 'for' loop and the 'while' loop. In Physics modeling, the 'for' loop is useful when one wants to check a condition before running the code in the 'for' loop. For example, the code following the statement -- 'for i in range(0,3):' -- will only run when i is within the specified range. The 'while' loop is useful when one wants to run a code for a specified interval or while a condition is true. For example, the code following the statement -- 'while t < 100:' -- will run until t is greater than or equal to 100 (1,2,3).
 
===A Mathematical Model===
When computing iterations for physics problems, using the iterative method with small delta t increments can produce near accurate results. To have truly small delta t increments, however, computational modeling is necessary for computation.
 
In a problem that requires use of the momentum principle and a specific number of time steps for iteration, we update momentum for each time step using the following equation:
<pre>
delta P = Fnet * deltat
</pre>
 
With this equation, the final momentum is updated after each time step (deltat) up to a time (t). We can only manually do this with a small number of increments, however, and as a result, with less accuracy than if our delta t increments were smaller. This is where computational modeling and VPython loops come in.
 
===A Computational Model===
With computational modeling using VPython, we can reduce the size of delta t and increase the number of time steps in the approximation of an iteration. Instead of two or three time steps, VPython loops make it possible to test infinitely small time steps, making the final result more accurate. For example, to calculate an approximation from t = 0 to t = 2 using two time steps, one could write the following time update:


==The Main Idea==
<pre>
deltat = 1
t = 0
while t < 2:
    t += deltat
</pre>


In programming, loops exist to execute a singular or series of statements for a specified number of times. This simplifies executing any function multiple times. Depending on the type of loop, the functions will know when to be carried out and how many time/for how long it will be carried out.
However, loops can be used to test much smaller time steps than deltat = 1; the smaller the time step, the more accurate the iteration.  


===For Loop===
==Examples==
The following examples cover a range of loops that can be created in VPython from the simplest 'for' loops to more complicated 'for' and 'while' loops.


For loops are based on a specified list and can repeat a function a specific number of times.
===Simple===
The simplest example is a basic 'for' loop. The following code will print each integer in a range:


====Examples====
<pre>
for i in range(0,10):
    print i
</pre>


For loops can be used in conjunction with a list of items or numbers.
The same thing can be accomplished with a 'while' loop as well. See the following:
<nowiki>
solarsystem = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
for planet in solarsystem:
    print(planet) </nowiki>
In the example of above a list will be printed as follows:


[[File:Planetlist.png]]
<pre>
i = 0
while i < 10:
    print i
    i += 1
</pre>


When modeling momentum updates, using a 'while' loop allows the code to run until Tfinal has been reached by adding deltat to t each time the loop runs.


For loops can also be used to complete a function for a certain number of times given as a range.  
===Middling===
<nowiki>
To solve more complex problems, we need to create values and objects before the loop that will then be updated within the loop until a certain time, t. In the following example, the final position and final velocity of object ball is updated until t = 10 using a time step of deltat = 1.
for x in range(0,3):
    print "I love physics!" </nowiki>
This will print the print the give phrase 3 times.


===While Loop===
<pre>
t = 0
deltat = 1


While loops are used to repeat a function until a certain value or criteria is met, which is generally less restrictive than a for loop.
while t < 10:
    Fgrav = vector(0,-ball.m*g,0)
    Fdrag=(.5)*dragCoeff*airDensity*areaBall*mag(ball.p/ball.m)**2*norm(ball.p)
    Fnet = Fgrav - Fdrag


====Examples====
    ball.p = ball.p + Fnet*deltat
While loops are very useful in physics for representing time intervals. For example, if you wanted to express that a object was moving over a certain time period you could represent it as such:
    ball.pos = ball.pos + (ball.p/ball.m)*deltat 
<nowiki>
#initial values
ball = sphere(pos=vector(0, 0, 0), radius=1)
time = 0
velocity = 5
#calculations
while time < 100
    time = time+10
    pos = velocity*time </nowiki>
This loop starts with the initial values of position = 0 meters, time = 0 seconds, and velocity = 5 m/s. The loop will run until the time value reaches 100 seconds. Inside the loop, time is first updated so that every iteration of the loop increases the time value (i.e. the first run of the loop time becomes 10 seconds, the second run time becomes 20 seconds, and so on). Next the position is updated using a physics formula: change in distance = velocity * time.


While loops can also be used to create objects in a pattern. For example, if you wanted to create series of spheres in a line you could use the following code:
     t += deltat
<nowiki>
#initial values
distance = 0
#calculations
while distance < 100:
     distance = distance + 10
    ball = sphere(pos=vec(distance,0,0) , radius=1)
</nowiki>


This loop will create a ball of the same radius in a line along the x axis every 10 meters. It's possible to alter distances along the y and z axis the same why simply by creating a variable for the y or z part of the vector.
print(ball.pos)    #prints final ball position
[[File:Balls_in_line.png]]
print(ball.p/mball)    #prints final ball velocity
</pre>


While loops can also be used to create objects in a circular path!
===Difficult===
<nowiki>
The following code calculates the final position and velocity of a ball attached to a string mounted to a ceiling. After code is written listing the constants, creating the objects, and setting an initial value of t = 0, the following statements update the position and velocity values until t = 10 seconds.
#initial values
theta = 0
#calculations
while theta < 2*pi:
    theta= theta + pi/6
    location = vector(cos(theta),sin(theta),0)
    ball = sphere(pos=(location), radius=0.1) </nowiki>
[[File:Balls_in_circle.png|200px]]


This code creates a series of 12 spheres in a circle by changing theta each time the loop is iterated. Changing the the increment by which theta is increased (in this case pi/6) you can change the number of spheres that are formed.
<pre>
t = 0
deltat = 1


while t < 10: 
    L = ball.pos - ceiling.pos
    s=mag(L) - L0
    Lhat = L/mag(L)
    Fs = -(ks)*s*Lhat
    Fg = vector(0,-g*mball,0)
    Fdrag = (-1)*b*(ball.p/mball)
    Fnet = Fg + Fs + Fdrag
    ball.p = ball.p + Fnet*deltat
    ball.pos = ball.pos + (ball.p/(mball))*deltat
    spring.axis = ball.pos - ceiling.pos
   
    t += deltat


print(ball.pos)    #prints final ball position
print(ball.p/mball)    #prints final ball velocity
</pre>


==History==
==Connectedness==
Understanding the basics of VPython creates a framework for more easily learning to write in coding languages other than Python. Additionally, understanding the basics of the 'for' loop and the 'while' loop enables one to write more complex code using both 'for' and 'while' loops, even nesting both types of loops in creating complex conditionals. In more advanced Physics modeling, being able to write more complex conditional statements enables these more complex equations and relationships to be solved via computational modeling.


The idea of loops predate computer programming, but the first instance of loops being used in this application was by [https://en.wikipedia.org/wiki/Ada_Lovelace Ada Lovelace] to calculate [https://en.wikipedia.org/wiki/Bernoulli_number Bernoulli numbers] which was described in 1842.
Even for non-computing majors, coding experience is a highly valuable trait employers are increasingly looking for in candidates. In 2016, analytics firm Burning Glass reported that programming jobs were growing 12% faster than the market average. Additionally, half of the projected job openings looking for programming experience are in non-technology fields such as 'finance, manufacturing, and healthcare' (4). In 2017, Forbes ranked Python as the top-ranked in-demand coding language among the top five: 'Python, Java, JavaScript, C#, and PHP' (5).  


== See also ==
==History==
Python is an interpreted language that originated in the 1980s and was released from development in the 1990s. Because it is interpreted, compiling is not required to convert lines of code into machine-understandable instructions (6). In 1998, David Scherer saw a need for a better 2D and 3D graphics programming environment and created the idea for Visual (a.k.a. VPython), a Python module (7).


===External links===
==See Also==
1. [https://wiki.python.org/moin/ForLoop More on For Loops]


2. [https://wiki.python.org/moin/WhileLoop More on While Loops]
===Further Reading===
'Why Coding Is Still The Most Important Job Skill Of The Future' (Dishman, 2016)
'The Five Most In-Demand Coding Languages' (Kauflin, 2017)


3. [http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/loops.html Loops and Sequences]
===External Links===
http://vpython.org/contents/docs/VisualIntro.html
http://vpython.org/contents/docs/
https://faculty.math.illinois.edu/~gfrancis/illimath/windows/aszgard_mini/pylibs/visual/docs/visual/VisualIntro.html
https://www.fastcompany.com/3060883/why-coding-is-the-job-skill-of-the-future-for-everyone
https://www.forbes.com/sites/jeffkauflin/2017/05/12/the-five-most-in-demand-coding-languages/#6b86011fb3f5
https://en.wikipedia.org/wiki/Python_(programming_language)
https://en.wikipedia.org/wiki/VPython#History




[[Category:VPython]]
==References==
1. http://vpython.org/contents/docs/VisualIntro.html
2. http://vpython.org/contents/docs/
3. https://faculty.math.illinois.edu/~gfrancis/illimath/windows/aszgard_mini/pylibs/visual/docs/visual/VisualIntro.html
4. https://www.fastcompany.com/3060883/why-coding-is-the-job-skill-of-the-future-for-everyone
5. https://www.forbes.com/sites/jeffkauflin/2017/05/12/the-five-most-in-demand-coding-languages/#6b86011fb3f5
6. https://en.wikipedia.org/wiki/Python_(programming_language)
7. https://en.wikipedia.org/wiki/VPython#History

Latest revision as of 02:52, 22 October 2019

An introduction to creating and using loops in VPython.

The Main Idea

The most commonly used loop structures in VPython are the 'for' loop and the 'while' loop. In Physics modeling, the 'for' loop is useful when one wants to check a condition before running the code in the 'for' loop. For example, the code following the statement -- 'for i in range(0,3):' -- will only run when i is within the specified range. The 'while' loop is useful when one wants to run a code for a specified interval or while a condition is true. For example, the code following the statement -- 'while t < 100:' -- will run until t is greater than or equal to 100 (1,2,3).

A Mathematical Model

When computing iterations for physics problems, using the iterative method with small delta t increments can produce near accurate results. To have truly small delta t increments, however, computational modeling is necessary for computation.

In a problem that requires use of the momentum principle and a specific number of time steps for iteration, we update momentum for each time step using the following equation:

delta P = Fnet * deltat

With this equation, the final momentum is updated after each time step (deltat) up to a time (t). We can only manually do this with a small number of increments, however, and as a result, with less accuracy than if our delta t increments were smaller. This is where computational modeling and VPython loops come in.

A Computational Model

With computational modeling using VPython, we can reduce the size of delta t and increase the number of time steps in the approximation of an iteration. Instead of two or three time steps, VPython loops make it possible to test infinitely small time steps, making the final result more accurate. For example, to calculate an approximation from t = 0 to t = 2 using two time steps, one could write the following time update:

deltat = 1
t = 0
while t < 2:
    t += deltat

However, loops can be used to test much smaller time steps than deltat = 1; the smaller the time step, the more accurate the iteration.

Examples

The following examples cover a range of loops that can be created in VPython from the simplest 'for' loops to more complicated 'for' and 'while' loops.

Simple

The simplest example is a basic 'for' loop. The following code will print each integer in a range:

for i in range(0,10):
    print i

The same thing can be accomplished with a 'while' loop as well. See the following:

i = 0
while i < 10:
    print i
    i += 1

When modeling momentum updates, using a 'while' loop allows the code to run until Tfinal has been reached by adding deltat to t each time the loop runs.

Middling

To solve more complex problems, we need to create values and objects before the loop that will then be updated within the loop until a certain time, t. In the following example, the final position and final velocity of object ball is updated until t = 10 using a time step of deltat = 1.

t = 0
deltat = 1

while t < 10:
    Fgrav = vector(0,-ball.m*g,0)
    Fdrag=(.5)*dragCoeff*airDensity*areaBall*mag(ball.p/ball.m)**2*norm(ball.p)
    Fnet = Fgrav - Fdrag

    ball.p = ball.p + Fnet*deltat
    ball.pos = ball.pos + (ball.p/ball.m)*deltat  

    t += deltat

print(ball.pos)    #prints final ball position
print(ball.p/mball)    #prints final ball velocity

Difficult

The following code calculates the final position and velocity of a ball attached to a string mounted to a ceiling. After code is written listing the constants, creating the objects, and setting an initial value of t = 0, the following statements update the position and velocity values until t = 10 seconds.

t = 0
deltat = 1

while t < 10:   
    L = ball.pos - ceiling.pos
    s=mag(L) - L0
    Lhat = L/mag(L)
    Fs = -(ks)*s*Lhat
    Fg = vector(0,-g*mball,0)
    Fdrag = (-1)*b*(ball.p/mball)
    Fnet = Fg + Fs + Fdrag
    ball.p = ball.p + Fnet*deltat
    ball.pos = ball.pos + (ball.p/(mball))*deltat
    spring.axis = ball.pos - ceiling.pos 
    
    t += deltat

print(ball.pos)    #prints final ball position
print(ball.p/mball)    #prints final ball velocity
 

Connectedness

Understanding the basics of VPython creates a framework for more easily learning to write in coding languages other than Python. Additionally, understanding the basics of the 'for' loop and the 'while' loop enables one to write more complex code using both 'for' and 'while' loops, even nesting both types of loops in creating complex conditionals. In more advanced Physics modeling, being able to write more complex conditional statements enables these more complex equations and relationships to be solved via computational modeling.

Even for non-computing majors, coding experience is a highly valuable trait employers are increasingly looking for in candidates. In 2016, analytics firm Burning Glass reported that programming jobs were growing 12% faster than the market average. Additionally, half of the projected job openings looking for programming experience are in non-technology fields such as 'finance, manufacturing, and healthcare' (4). In 2017, Forbes ranked Python as the top-ranked in-demand coding language among the top five: 'Python, Java, JavaScript, C#, and PHP' (5).

History

Python is an interpreted language that originated in the 1980s and was released from development in the 1990s. Because it is interpreted, compiling is not required to convert lines of code into machine-understandable instructions (6). In 1998, David Scherer saw a need for a better 2D and 3D graphics programming environment and created the idea for Visual (a.k.a. VPython), a Python module (7).

See Also

Further Reading

'Why Coding Is Still The Most Important Job Skill Of The Future' (Dishman, 2016) 'The Five Most In-Demand Coding Languages' (Kauflin, 2017)

External Links

http://vpython.org/contents/docs/VisualIntro.html http://vpython.org/contents/docs/ https://faculty.math.illinois.edu/~gfrancis/illimath/windows/aszgard_mini/pylibs/visual/docs/visual/VisualIntro.html https://www.fastcompany.com/3060883/why-coding-is-the-job-skill-of-the-future-for-everyone https://www.forbes.com/sites/jeffkauflin/2017/05/12/the-five-most-in-demand-coding-languages/#6b86011fb3f5 https://en.wikipedia.org/wiki/Python_(programming_language) https://en.wikipedia.org/wiki/VPython#History


References

1. http://vpython.org/contents/docs/VisualIntro.html 2. http://vpython.org/contents/docs/ 3. https://faculty.math.illinois.edu/~gfrancis/illimath/windows/aszgard_mini/pylibs/visual/docs/visual/VisualIntro.html 4. https://www.fastcompany.com/3060883/why-coding-is-the-job-skill-of-the-future-for-everyone 5. https://www.forbes.com/sites/jeffkauflin/2017/05/12/the-five-most-in-demand-coding-languages/#6b86011fb3f5 6. https://en.wikipedia.org/wiki/Python_(programming_language) 7. https://en.wikipedia.org/wiki/VPython#History