第一个函数是一个简单的二进制搜索实现,用于查找数字的平方根:
def sqrt1(x):
if x < 0:
raise ValueError(x)
if x > 0:
if x < 1:
root = 1
while root ** 2 > x:
root /= 2
half = root
while root ** 2 != x:
half /= 2
diff = root + half
if diff == root:
return root
if diff ** 2 <= x:
root = diff
return root
if x > 1:
root = 1
while root ** 2 < x:
root *= 2
half = root / 2
while root ** 2 != x:
half /= 2
diff = root - half
if diff == root:
return root
if diff ** 2 >= x:
root = diff
return root
return 1
return 0
第二个函数做同样的事情,但比第一个更简单,速度快 15 倍:
def sqrt2(z):
assert z > 0
x, y = z, None
while x != y:
y = x
x = (x + z / x) / 2
return x
- 为什么
sqrt2
比 快那么多sqrt1
? - 可以
sqrt1
做成表演更喜欢sqrt2
吗?