VPython Loops: Difference between revisions
No edit summary |
|||
Line 1: | Line 1: | ||
Claimed by Nick Franco (Spring 2017) | |||
Claimed by Nicolas Castro (Fall 2016) | Claimed by Nicolas Castro (Fall 2016) | ||
Revision as of 17:49, 5 April 2017
Claimed by Nick Franco (Spring 2017) Claimed by Nicolas Castro (Fall 2016)
An introduction into iteration in VPython and the implementation of loops.
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.
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 these values 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 iteration to have the script run 50 times or until a condition is met. This gives 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:
for x in range(0, 3): print x
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.
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:
values = [10, 15, 20] for q in values: r = q + 10 print r
This function goes through each value in values, adds 10, and prints the result.
We can also set it to be the length of a list or even a string, as shown below:
string1 = "Dank Memes" for g in string1: print g
This function will loop through each letter of the string stored in 'string1' and print that letter.
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:
from __future__ import division from visual import * # Initial conditions and constants fnet = vector(3, 2, 0) #N, some constant force deltat = 1 #s, a time interval p = vector(18, 24, 9) #kgm/s, some initial momentum m = 3 #kg, mass of object r = (10, 35, 2) #m, some initial position # Calculation Loop for t in range(0,49): # looping for 50 'seconds' (times) p = p + fnet*deltat # updates momentum using defined values v = p/m # finds velocity r = r + v*deltat # updates position # loop ends or repeats if t is still in the range(0,49) print p # prints final momentum print v # prints final velocity print r # prints final position
Essentially, the code repeats fifty times, 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.
The While Loop
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.
Examples
Below is an example of what a basic while loop looks like. The header has the keyword while followed by a logical expression.
while x < 10: x = x + 1
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 for x 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.
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.
from __future__ import division from visual import * # Initial conditions and constants fnet = vector(3, 2, 0) #N, some constant force deltat = 1 #s, a time interval 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 # Calculation Loop while pmag < 100: # loop will repeat until this expression becomes false p = p + fnet*deltat # momentum is calculated using defined values pmag = mag(p) # magnitude is found t = t + 1 # t is updated to count this loop # loop ends or repeats if pmag < 100 print t # prints the time (time cycles) it took to reach a magnitude of 100 kgm/s.
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 using the initial conditions to begin. 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.
Nested Loops
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.
bigList = [[1,2,3],['a','b','c'],[0,0,0]] for x in bigList: for y in x: print y
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.
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:
j = 1 while j < 10 j = j + 1 if j == 3 break #remaining code
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
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:
ball = sphere(pos=vector(0,0,0), radius=1, color=color.red)
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:
from __future__ import division from visual import * # Initial conditions and constants 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, a time interval pball = vector(18, 24, 9) #kgm/s, the ball's initial momentum mball = 3 #kg, the ball's mass t = 0 # some start time # Calculation loop while t <= 100: rate(1) pball = pball + fnet*deltat # updates momentum vball = pball/mball # finds velocity ball.pos = ball.pos + vball*deltat # updates position t = t + deltat # loop ends or repeats if t < 100 print pball # prints final momentum print vball # prints final velocity print ball.pos # prints final position
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 VPython 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
The idea of loops predate computer programming, but the first instance of loops being used in this application was by Ada Lovelace to calculate Bernoulli numbers which was described in 1842.
See also
VPython
VPython basics
VPython Animation
Further Understanding
https://www.youtube.com/watch?v=ZwhU-K9Zv5k
https://www.youtube.com/watch?v=cNdPqgNFeVk
External links
References
http://vpython.org/contents/docs/VisualIntro.html
http://vpython.org/contents/docs/
http://secant.cs.purdue.edu/_media/lab3_for_loopshhs.pdf