VPython Loops: Difference between revisions

From Physics Book
Jump to navigation Jump to search
No edit summary
No edit summary
Line 11: Line 11:
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.
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.


===For Loop===
===The For Loop===


For loops are based on a specified list and can repeat a function a specific number of times.
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====
====Examples====


For loops can be used in conjunction with a list of items or numbers.
Below is an example:
  <nowiki>
  <nowiki>
solarsystem = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
for x in range(0, 3):
for planet in solarsystem:
     print x </nowiki>
     print(planet) </nowiki>
In the example of above a list will be printed as follows:


[[File:Planetlist.png]]
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:
For loops can also be used to complete a function for a certain number of times given as a range.
  <nowiki>
  <nowiki>
for x in range(0,3):
for x in range(0,3):
     print "I love physics!" </nowiki>
     print "I love physics!" </nowiki>
This will print the print the give phrase 3 times.


===While Loop===
We can also set it to be the length of a list or even a string, as shown below:
<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.


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.
===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====
====Examples====
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:
 
Below is an example of what a basic while loop looks like. The header has the keyword while followed by a logical expression.
  <nowiki>
  <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:
                            </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.
 
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.
  <nowiki>
  <nowiki>
#initial values
 
distance = 0
#calculations
while distance < 100:
    distance = distance + 10
    ball = sphere(pos=vec(distance,0,0) , radius=1)
  </nowiki>
  </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. Once the loop ends, we have found our final time.


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.
==Nested Loops==
[[File:Balls_in_line.png]]


While loops can also be used to create objects in a circular path!
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.
  <nowiki>
  <nowiki>
#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.
</nowiki>
 
==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>
</nowiki>
==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:
<nowiki>
</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>
</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==

Revision as of 16:26, 27 November 2016

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

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:

for x in range(0,3):
    print "I love physics!" 

We can also set it to be the length of a list or even a string, as shown below:

                            

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:

                            

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.

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.


                            

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.

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.


 

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.

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.


 

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:


 

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:

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:

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

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

External links

1. More on For Loops

2. More on While Loops

3. Loops and Sequences