CS 190C LAB 2: Friday, January 23, 2009

Demo Problems

import math

def main():
y = input('Enter number of terms for approximation of e: ')
total = 0.0
fac = 1
for i in range(y):
total += 1.0 / fac
fac *= i + 1
print 'The approximated value of e is:', total
print 'The actual value from math.e is:', math.e

main()

Generating Random Numbers

There are two ways to generate random decimal numbers in Python. Both require:

import random

The random module has two functions, random() and uniform(), that you can use to generate random functions. The two function calls below are equivalent (obviously the generated numbers will be different, or they are not very random):

>>> import random
>>> random.random()
0.28745840659531663
>>> random.uniform(0, 1)
0.97838921930186273

In-Lab Problem

Write a Python program to approximate the value of pi using a modified Leibniz formula. Our approximation is as follows:

$\pi ~~ =~~ 4\sum_{i=0}^\infty \frac{(-1)^i}{2i+1} ~~=~~ \frac{4}{1} - \frac{4}{3} + \frac{4}{5} - \frac{4}{7} + \frac{4}{9} + \cdots$

You should ask the user for input n, the number of terms to use for the approximation. It would be a good idea to test approximations for n = 100, 1000, 10000, and 100000. Of course, the more terms you use in the approximation, the more accurate it should be. Print your approximated value of pi and the actual value of pi from the Python math module. Then print the relative error, which is simply:

$\frac{|\pi_{approx} - \pi|}{\pi}$

# CS190C: Spring 2009
# FirstName LastName
# Lab 2

import math

def main():
#This is where your code should go

main()

Save your file in a file called lab2.py. Remember to include the .py in the filename, because IDLE will not automatically add it for you.

Solution

import math

def main():
y = input('Enter number of terms for approximation of pi: ')
total = 0.0
for i in range(y):
if i % 2 == 0:
total += 4.0 / (2*i + 1)
else:
total -= 4.0 / (2*i + 1)
print 'The approximated value of pi is:', total
print 'The actual value from math.pi is:', math.pi
print 'The relative error is:', abs(math.pi - total) / math.pi

main()