Newton’s Method in Python
def sqrt(n):
"""
This method calculates the square root
of a value using Newton's method to an
accuracy of within sigma.
"""
sigma = 0.0001
# The first guess is n / 2
# (which only works when n is 4)
guess = n / 2
while abs(n - guess * guess) > sigma:
# Compute the quotient
quotient = n / guess
# Average the quotient and the current guess
guess = (quotient + guess) / 2
return guess
Estimating Pi with the Pythagorean Theorem and Random Numbers
import random
def main():
TOTAL_PECKS = 100000
hits = 0
i = 0
while i < TOTAL_PECKS:
x = random.random() * 2 - 1
y = random.random() * 2 - 1
if x * x + y * y <= 1:
hits += 1
i += 1
pi = 4.0 * float(hits) / TOTAL_PECKS
print "Estimate Pi:", pi
main()
Rabin-Miller in Python
import random
import sys
def isProbablyPrime(n, k=5):
"""
This algorithm computes if 'n' is probably prime
through a series of 'k' trials using Rabin-Miller. Set k to
be something reasonable, like 5.
http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
"""
if n%2 == 0:
return False
d = n - 1
s = 0
while d % 2 == 0:
d /= 2
s += 1
i = 0
while i < k:
a = random.randint(2, n-2)
x = fastExponentialMod(a, d, n)
if x == 1 or x == n-1:
i += 1
continue
pleaseContinue = False
r = 1
while r < s:
x = x*x % n
if x == 1:
return False
if x == n - 1:
pleaseContinue = True
break
r += 1
if pleaseContinue == False:
return False
i += 1
return True
def fastExponentialMod(b, e, m):
"""
This algorithm quickly computes "b ** e % m",
but in a manner that is faster than explicitly
saying "b ** e % m".
I believe this algorithm was originally crafted
by Bruce Schneier.
"""
r = 1
while e > 0:
if e % 2 == 1:
r = (r * b) % m
e /= 2
b = (b*b) % m
return r
Finding all of the permutations of a sequence (Python)
def permutations(seq):
if len(seq) == 1:
return [seq]
i = 0
perms = []
while i < len(seq):
elem = seq.pop(i)
latter_perms = permutations(seq)
for perm in latter_perms:
perms.append([elem] + perm)
seq.insert(i, elem)
i += 1
return perms