Skip to content

Instantly share code, notes, and snippets.

@huseyinyilmaz
Created April 7, 2011 13:07
Show Gist options
  • Save huseyinyilmaz/907747 to your computer and use it in GitHub Desktop.
Save huseyinyilmaz/907747 to your computer and use it in GitHub Desktop.
square-root performance test between native implementation and Newton's method.
import random
import operator
from datetime import datetime
from math import sqrt
from functools import reduce
def better_gues(number,gues):
return ((number/gues) + gues) /2
def sqrt1(number,gues=None):
if gues is None:
gues = number/2
if abs(number - gues*gues) <0.001:
return gues
else:
return sqrt1(number,better_gues(number,gues))
#tests
if __name__ == '__main__':
SIZE = 10000000
# create test lists
l = [random.random()*SIZE*10 for i in range(SIZE)]
l1 = l[:]
l2 = l[:]
start = datetime.now()
l1 = map(sqrt,l1)
end = datetime.now()
print('native',str(end-start))
start = datetime.now()
l2 = map(sqrt1,l2)
end = datetime.now()
print('our version',str(end-start))
avrg = reduce(operator.add, map(lambda x,y:x-y,l1,l2))/SIZE
print('l3 =', avrg)
##########################
# PRINTED SAMPLE RESULTS #
##########################
# Results for python 2.6.6
# ('native', '0:00:01.095318')
# ('our version', '0:01:50.710895')
# ('l3 =', -7.1736151821178763e-09)
# Results for python 3.2
# native 0:00:00.000084
# our version 0:00:00.000005
# l3 = -7.18527774924e-09
(define (average x y) (/ (+ x y) 2))
(define (square x) (* x x))
(define (abs x)(if (< x 0) (- x) x))
(define (better_guess number guess)
(average (/ number guess) guess)
)
(define (calculate_square_root number guess)
(if (< (abs (- (square guess) number)) 0.001)
guess
(calculate_square_root number (better_guess number guess))
)
)
(define (sqrt1 x)
(calculate_square_root x (/ x 2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment