In [6]:
def print_n(s, n):
while n > 0:
print(s)
n -= 1
In [7]:
print_n('hi there', 3)
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]:
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)
In [1]:
def eval_loop():
while True:
user_input = raw_input(">")
if user_input == "done":
break
print eval(user_input)
In [5]:
eval_loop()
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]:
In [21]:
estimate_pi() - math.pi
Out[21]:
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]:
In [23]:
math.pi - estimate_pi()
Out[23]: