Lecture 4

Harold Nelson

1/25/2018

Getting Help in Python

Run these following batches of commands by hand in the python shell.

help(turtle)
help('turtle')

import turtle
help(turtle)

import turtle
joe = turtle.Turtle()
help('joe')
help(joe)

What can you infer about the use of help() from these examples?

The math Module

Run the following batches of commands by hand in the python shell.

print(2**.5)
print(sqrt(2))

import math
print(math.sqrt(2))

print(pi)

print(math.pi)

What does this tell you?

When you start python, it has very limited mathematical capabilities. If you import the math module, python gains a lot of mathematics.

Approximation of \(\pi\)

See the publisher’s powerpoint starting with slide 4.

Code for the archimedes approach.

import math

def archimedes(numSides):
    
    innerangleB = 360.0/numSides
    halfangleA = innerangleB/2

    onehalfsideS = math.sin(math.radians(halfangleA))

    sideS = onehalfsideS * 2

    polygonCircumference = numSides * sideS
    pi = polygonCircumference/2

    return pi

# Test it
pi_est = archimedes(10)
print(pi_est)
## 3.09016994375

Question:

How many sides does it take to get a good approximation of \(\pi\)?

A better question: How do we measure the quality of an approximation.

Answer

All of these estimates are low. We can measure the quality by taking the ratio of the estimate to the true value given by math.pi.

Problem:

Write python code to compute the sum of the first 4 integers.

Answer

total = 0
for i in range(1,5):
    total = total + i
print(total)    
## 10

Problem:

Write a python function to compute the sum of the first N integers. Test it by using 4 as the input.

def sum_first_N(N):
    total = 0
    for i in range(1,N+1):
        total = total + i
    return total 
    
testval = sum_first_N(4)
print(testval)
## 10

Problem:

Write a python function to compute the average of the first N integers.

Answer

def avg_first_N(N):
    total = 0
    count = 0 # Could avoid, but...
    for i in range(1,N+1):
        total = total + i
        count = count + 1.0
    avg = total/count
    return avg
testavg = avg_first_N(4)
print(testavg)
## 2.5

Problem:

Write python code to calculate the product of the first 4 integers.

Answer:

prod = 1
for i in range(1,5):
    prod = prod * i
print(prod)    
## 24

Problem:

Write a python function to compute the product of the first N integers.

Answer

def pfN(N):
    prod = 1
    for i in range(1,N+1):
        prod = prod * i
    return prod
    
# Test with 4
print(pfN(4))

# Test with 10
print(pfN(10))
    
## 24
## 3628800