最初の関数は、数値の平方根を見つけるための単純な二分探索の実装です。
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
2番目の関数は同じことを行いますが、最初の関数よりも単純で約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
か?