# loops.py
# Walker M. White (wmw2)
# October 30, 2012
"""Module to illustrate difference between for-loops and while-loops"""
def increment_for(seq):
"""Increment each element of seq
Precondition: seq is a list of integers"""
for k in range(len(seq)):
seq[k] = seq[k]+1
def increment_while(seq):
"""Increment each element of seq
Precondition: seq is a list of integers"""
k = 0
while k < len(seq):
seq[k] = seq[k]+1
k = k + 1
def e(err):
"""Compute the constant e to with the given margin of error.
Use the Taylor Expansion e = 1 + 1 + 1/2 + 1/6 + ... + 1/n! + ...
We can approximate e ~ 1 + 1 + 1/2 + 1/6 + ... + 1/n!
(e.g. stopping the infinite sum at some value of n). The
error when we do this is < 1/n!. So we loop until we reach
a value of n with 1/n! <= error.
Precondition: err > 0 is a number."""
value = 2 # The value of e start with n = 1
factorial = 1 # Tracks factorial without recursion
n = 2 # The next value of n
while 1.0/factorial > err:
factorial = factorial*n # Compute 1/n!
value = value + 1.0/factorial # Add 1/n!
n = n + 1
return value