Exercise 7.1


In [6]:
def print_n(s, n):
    while n > 0:
        print(s)
        n -= 1

In [7]:
print_n('hi there', 3)


hi there
hi there
hi there

Exercise 7.2


In [51]:
def square_root(a):
    epsilon = 1e-7
    x = a / 2.
    while True:
        y = (x + a/x) / 2
        if abs(x - y) < epsilon:
            break
        x = y
    return x

In [40]:
square_root(144)


Out[40]:
12.000000010666378

Exercise 7.3


In [49]:
import math
def test_square_root(a_lo, a_hi):
    for a in range(a_lo, a_hi+1):
        actual = math.sqrt(a)
        approx = square_root(a)
        error = abs(actual - approx)
        print "{}\t{}\t{}\t{}".format(a, actual, approx, error)

In [52]:
test_square_root(1, 9)


1	1.0	1.00000004646	4.64611473738e-08
2	1.41421356237	1.41421356237	1.59472435257e-12
3	1.73205080757	1.73205081001	2.44585018905e-09
4	2.0	2.0	0.0
5	2.2360679775	2.23606797792	4.16013890003e-10
6	2.44948974278	2.44948979592	5.31351895816e-08
7	2.64575131106	2.64575131106	1.02584607475e-13
8	2.82842712475	2.82842712475	3.18944870514e-12
9	3.0	3.00000000004	3.9321434997e-11

Exercise 7.4


In [1]:
def eval_loop():
    while True:
        user_input = raw_input(">")
        if user_input == "done":
            break
        print eval(user_input)

In [5]:
eval_loop()


>324 * 89324
28940976
>done

Exercise 7.5


In [15]:
import math

def estimate_pi():
    k = 0.
    term_min = 1e-15
    term = term_min + 1 # need to get in to the loop
    term_sum = 0
    const_factor = 2 * math.sqrt(2) / 9801
    while abs(term) > term_min:
        numer = math.factorial(4*k) * (1103 + 26390*k)
        denom = math.factorial(k)**4 * 396**(4*k)
        term = numer / denom
        term_sum += term
        k += 1
        print term

    return 1 / (const_factor * term_sum)

In [20]:
estimate_pi()


Out[20]:
3.141592653589793

In [21]:
estimate_pi() - math.pi


Out[21]:
0.0

In [17]:
import math

def estimate_pi():
    k = 0.
    term_sum = 0
    const_factor = 2 * math.sqrt(2) / 9801
    while True:
        numer = math.factorial(4*k) * (1103 + 26390*k)
        denom = math.factorial(k)**4 * 396**(4*k)
        term = numer / denom
        term_sum += term
        if abs(term) < 1e-15: break
        k += 1

    return 1 / (const_factor * term_sum)

In [22]:
estimate_pi()


Out[22]:
3.141592653589793

In [23]:
math.pi - estimate_pi()


Out[23]:
0.0