VPython Loops: Difference between revisions

From Physics Book
Jump to navigation Jump to search
No edit summary
No edit summary
 
(22 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 the final momentum 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.
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===
 
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.
 
====Examples====
 
Below is an example:
<nowiki>
for x in range(0, 3):
    print x </nowiki>


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


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:  
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:
<nowiki>
<pre>
for x in range(0,3):
delta P = Fnet * deltat
    print "I love physics!" </nowiki>
</pre>


We can also set it to be the length of a list or even a string, as shown below:
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.  
<nowiki>
                            </nowiki>
For a final example on how we can use for loops, lets revisit our problem of updating momentum over 50 seconds. Take a look at the code below:
<nowiki>
                            </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.
===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 While Loop===
<pre>
deltat = 1
t = 0
while t < 2:
    t += deltat
</pre>


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


Below is an example of what a basic while loop looks like. The header has the keyword while followed by a logical expression.
===Simple===
<nowiki>
The simplest example is a basic 'for' loop. The following code will print each integer in a range:


                            </nowiki>
<pre>
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.
for i in range(0,10):
    print i
</pre>


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, say, 100 kg*m/s.
The same thing can be accomplished with a 'while' loop as well. See the following:
<nowiki>


</nowiki>
<pre>
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. Once the loop ends, we have found our final time.
i = 0
while i < 10:
    print i
    i += 1
</pre>


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


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


</nowiki>
<pre>
t = 0
deltat = 1


==Breaking a 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


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:
    ball.p = ball.p + Fnet*deltat
  <nowiki>
    ball.pos = ball.pos + (ball.p/ball.m)*deltat  


</nowiki>
    t += deltat


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


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


==Animation==
<pre>
t = 0
deltat = 1


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:
while t < 10: 
<nowiki>
    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


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


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


<nowiki>
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).  
 
</nowiki>
 
With this code, we model a ball moving through space as we update its position and update time intervals. This is a brief overview on animation, take a look at this page for more.


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