VPython Loops: Difference between revisions

From Physics Book
Jump to navigation Jump to search
No edit summary
No edit summary
 
(17 intermediate revisions by 3 users not shown)
Line 1: Line 1:
Claimed by Nicolas Castro (Fall 2016)
An introduction to creating and using loops in VPython.
 
An introduction into iteration in VPython and the implementation of loops.


==The Main Idea==
==The Main Idea==
In VPython, loops are essential in order to create animations, repeat a calculation multiple times, or complete some task that must be done until a condition is met. Loops are based on the concept of iteration. Iteration is simply the repetition of a block of code and looping is the implementation of this 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).


Let’s say that we needed to find an accurate final momentum, velocity and position of an object over five seconds with a time interval of one second. Given the initial conditions, we could do this problem by hand fairly quickly. Now, let’s say you needed to find the final momentum after 50 seconds. We can still definitely do this problem by hand, except it will take substantially longer. Using VPython, we can solve this problem very simply. We can write a script that will calculate the final momentum at each time interval and then use looping to have the script run 50 times or until a condition is met. This makes our lives way easier and can give us the answer to our problem in no time.
===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.  
Using the concept of iteration and implementing it with loops allows us to take many repeated calculations or updates and condense the problem into a few lines of code that will simply be repeated. Without looping, we would do this problem by hand, making it quite cumbersome to do. Therefore, loops are extremely useful, in that it makes coding in any language significantly more efficient and allows us to break down large problems into a series of small repeated calculations.
We can use iteration through two types of loops: ‘while’ loops and ‘for’ loops. Each has its own purpose and both are useful in their own situations.


===The For Loop===
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>


The ‘for’ loop is a loop that will repeat a block of code for a defined number of times. This is useful, for example, if we need to find the final momentum after a certain amount of time. In order to write a ‘for’ loop, we need to use the keyword for followed by a variable in some defined range, which will be the range we iterate over. Following this header, we write the code we want repeated.
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.  


====Examples====
===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:


Below is an example:
<pre>
<nowiki>
deltat = 1
for x in range(0, 3):
t = 0
     print x </nowiki>
while t < 2:
     t += deltat
</pre>


Here we see that the loop will repeat three times, when x is 0, 1, and 2 from the header. When we run this, the computer will read the header and initialize the loop. It will start with setting x = 0. Then, it will move to the body of the loop and execute the block with x = 0. Once the block is complete, or in this case once x is printed, the computer will return all the way back up to the header and set x = 1. This will continue until the computer completes the final iteration. It will then check the header and see that of three times, the code has been run three times and then exit the loop.
However, loops can be used to test much smaller time steps than deltat = 1; the smaller the time step, the more accurate the iteration.  


There are many different ways to set the range we want to iterate over. For example, we can set it to be a list, as shown below:
==Examples==
<nowiki>
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.
values = [10, 15, 20]
for q in values:
    r = q + 10
    print r </nowiki>


This function goes through each value in values, adds 10, and prints the result.
===Simple===
The simplest example is a basic 'for' loop. The following code will print each integer in a range:


We can also set it to be the length of a list or even a string, as shown below:
<pre>
<nowiki>
for i in range(0,10):
string1 = "Dank Memes"
     print i
for g in string1:
</pre>
     print g </nowiki>


This function will loop through each letter of the string stored in 'string1' and print that letter.
The same thing can be accomplished with a 'while' loop as well. See the following:


For a final example on how we can use for loops, lets revisit our problem of updating an object's momentum over 50 seconds. Take a look at the code below:
<pre>
<nowiki>
i = 0
from __future__ import division
while i < 10:
from visual import *
     print i
fnet = vector(3, 2, 0) #N, some constant force
     i += 1
deltat = 1 #s
</pre>
p = vector(18, 24, 9) #kgm/s
m = 3 #kg
r = (10, 35, 2) #m, some initial position
for t in range(0,49):   # looping for 50 seconds
     p = p + fnet*deltat  # updates momentum
     v = p/m  # finds velocity
    r = r + v*deltat  # updates position
# loop ends
print p # prints final momentum
print v # prints final velocity
print r # prints final position </nowiki>


Essentially, the code repeats for the fifty seconds, and for each deltat the code block containing the momentum principle is calculated. Once the loop is run through, we end up with our final answer, making this tedious problem into a simple one.
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.


===The While Loop===
===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.


The second type of loop we have is called the ‘while’ loop. This type of loop will run until a set logical expression is met. For example, to again revisit our momentum problem, let’s say instead of finding the final momentum after 50 seconds, I wanted to see how long it takes for a defined momentum value to be met. Before we tackle this, let’s take a look at how we might approach a while loop.
<pre>
t = 0
deltat = 1


====Examples====
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


Below is an example of what a basic while loop looks like. The header has the keyword while followed by a logical expression.
    ball.p = ball.p + Fnet*deltat
<nowiki>
     ball.pos = ball.pos + (ball.p/ball.m)*deltat 
while x < 10:
     x = x + 1 </nowiki>


The code above is checking to see when x is less than 10. Always remember to initialize the variable before the loop, so a starting value exists. To begin, the computer reads the header and immediately checks if x is less than 10. Since x is 0, this is true, causing the computer to enter the loop and execute the block of code inside the loop, essentially ticking up the value of x by one. Once the code body is read and complete, the computer then checks the logical expression again. Since x = 1, it is less than 10, again, making the statement true. This repeats until x = 11. Once the computer checks this and finds that 11 ~< 10, it will break out of the loop.
    t += deltat


While loops are fairly straight forward and can have any type of logical expression to define them. Now, let’s look into our original example. Below is the code through which we find the time at which we reach a final momentum of magnitude, say, 100 kgm/s.
print(ball.pos)    #prints final ball position
<nowiki>
print(ball.p/mball)    #prints final ball velocity
from __future__ import division
</pre>
from visual import *


fnet = vector(3, 2, 0) #N, some constant force
===Difficult===
deltat = 1 #s
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.
p = vector(18, 24, 9) #kgm/s
pmag = mag(p) #kgm/s, magnitude of momentum
t = 0 # Counter that will keep track of the time passed
while pmag < 100:
    p = p + fnet*deltat
    pmag = mag(p)
    t = t + 1
# loop ends
print t # prints the time (time cycles) it took to reach a magnitude of 100 kgm/s. </nowiki>


With this while loop, or logical expression is checking to see when p < 100. The computer will then cycle through the code and repeat the momentum principle calculation until p > 100. Meanwhile, with each cycle, we have the variable t 'counting' how many loops of 1 second (deltat) have passed. Once the loop ends, we have found our final time as the variable t.
<pre>
t = 0
deltat = 1


==Nested Loops==
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


Now that we know the basic loop structures and how to use them, we can start combining these loops using something called a ‘nested loop’. Nesting loops is helpful when you have a list of lists or some sort of matrix through which you want to iterate through every value. The reason this is helpful is because with two loops running at the same time, we can move through a matrix or list of lists in two dimensions. The code below shows how we might implement a nested loop.
print(ball.pos)    #prints final ball position
  <nowiki>
print(ball.p/mball)    #prints final ball velocity
bigList = [[1,2,3],['a','b','c'],[0,0,0]]
  </pre>
for x in bigList:
    for y in x:
        print y </nowiki>


This script will go through bigList and print each element. The first for loop will go through each list in bigList, starting with [1,2,3]. The second for loop then goes through this selected list and prints each element. Once the inner loop finishes, the outer loop continues by taking the next list in bigList.
==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.  
==Breaking a Loop==
 
Putting the keyword ‘break’ in your code causes the loop to be stopped and broken out of once break is executed. This is useful when you might want to find if some specific instance in your code occurs before the final value is reached. Example:
<nowiki>
j = 1
while j < 10
    j = j + 1
    if j == 3
        break
#remaining code </nowiki>
 
This loop will tick j up 1, except when j reaches three, a conditional statement will cause the loop to 'break'. The computer will stop reading the looped code and execute the remaining code.
 
==Infinite Loops==
 
Infinite loops often occur when the logical expression of a while loop is not met. If your code seems to run for an excessively long time, stop the program and check your code to see if the terminating logical expression is being approached.


==Animation==
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).


We’ve seen how iteration can be used to repeat calculations. This can be taken a step further to animation. We can make animation in VPython by using loops to update the position of objects at a certain time t. In order to animate an object, we need to update position and update time. For example, we can define some ball to start:
<nowiki>
ball = sphere(pos=vector(0,0,0), radius=1, color=color.red) </nowiki>
Now, with the following loop we can update its position due to some force acting on it over some time t and then update time to begin the next time step. Look at the following code:
<nowiki>
from __future__ import division
from visual import *
ball = sphere(pos=vector(0,0,0), radius=1, color=color.red) #ball created
fnet = vector(3, 2, 0) #N, some constant force
deltat = 1 #s
pball = vector(18, 24, 9) #kgm/s
mball = 3 #kg
t = 0 # some start time
while t <= 100:
    rate(1)
    pball = pball + fnet*deltat  # updates momentum
    vball = pball/mball  # finds velocity
    ball.pos = ball.pos + vball*deltat  # updates position
# loop ends
print pball # prints final momentum
print vball # prints final velocity
print ball.pos # prints final position  </nowiki>
With this code, we model a ball moving through space as we update its position and update time intervals. This is only a brief overview on animation, take a look at the animation page for more information. Notice how similar this code is to our previous examples.
==Connectedness==
  1. How is this topic connected to something that you are interested in? I've always wanted to really understand coding. Looping is commonplace and a staple in all programming languages, so understanding this is one of the first steps to being experienced with coding. It is interesting to see how each language sets up its loops and how it defines the looping parameters. And yet in the end, the same goal is accomplished. This topic is a basis for coding efficiently, something I am interested in.
  2. How is it connected to your major? My major happens to be BME, which may not be directly related to looping, but it does make a wide use of programming. Medical devices need operating systems, GUIs, and much more, all of which are developed from coding. Therefore, program experience is required in the field of Biomedical Engineering, even if the two subjects seem quite dissimilar.
  3. Is there an interesting industrial application? Knowing how to code is becoming an essential skill in industry. With automation as common as it is, knowing how the computer systems that drive the automation function, coding has its applications in industry. Knowing how to manipulate code to solve complex problems is definitely an advantage, making coding very important in modern industry.
==History==
==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).


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.
==See Also==
 
== See also ==
 
===External links===
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