epsilon = 0.0000001
def square_root(a):
x = a / 2.0
while True:
y = (x + a / x) / 2
if abs(y - x) < epsilon:
break
x = y
return y
def test_square_root():
import math
for i in range(1, 10):
mine = square_root(i)
theirs = math.sqrt(i)
delta = abs(mine - theirs)
# Old style string formatting.
# %-13.11g
# - = left justified
# 13 = total number of characters for field
# 11 = number of characters after decimal point
# g = floating point number or scientific notation (shorter wins)
# print("%3.1f %-13.11g %-13.11g %.11g"
# % (float(i), mine, theirs, delta))
# New style string formatting.
# print("{:3.1f} {:<13.11g} {:<13.11g} {:.11g}".format(
# float(i), mine, theirs, delta))
# New style string formatting with named arguments.
# Note that multiple string constants with no operators
# between them are concatenated together and treated as
# a single string constant.
print("{number:3.1f} {estimate:<13.11g} "
"{sqrt:<13.11g} {difference:.11g}".format(
number=i, estimate=mine, sqrt=theirs, difference=delta))
test_square_root()