# numerical.py # Walker M. White (wmw2) # November 5, 2013 """Module to show while-loops and numerical computations. This is one of the most powerful uses of a while loop: using it to run a computation until it converges. There are a lot of algorithms from Calculus and Numerical Analysis that work this way. In addition, this is how we approach the clustering example from A5""" def sqrt(c,err=1e-6): """Returns: the square root of c to with the given margin of error. Use Newton's Method to find the root of the polynomial f(x) = x^2-c Newton's Method produces a sequence where x_(n+1) = x_n - f(x_n)/f'(x_n) = x_n - (x_n*x_n-c)/(2x_n) which we simplify to x_(n+1) = x_n/2 + c/2 x_n We can stop this process and use x_n as an approximation of the square root of c. The error when we do this is less than |x_n*x_n - c|. So we loop until this error is less than err. Precondition: c, err > 0 is a number.""" x = c/2.0 while abs(x*x-c) > err: # Compute next in Newton's Method sequence x = x/2.0+c/(2.0*x) return x def e(err): """Returns: 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