尝试在 Python 中为我的 sqrt 函数计时

Trying to timeit my sqrt function in Python

所以我尝试编写一个简单的平方根函数。我做了,我想将它与 Python 的原始版本进行比较。这是我的代码:

from math import sqrt
import timeit

def sqrt2(number):
    i=1
    while i**2<number:
        i+=1
    left=float(i-1)
    right=float(i)
    temp = left+(right-left)/2
    while str(temp**2)!=str(number):
        if temp**2>number:
            right=temp
            temp = left+(right-left)/2
        elif temp**2<number:
            left=temp
            temp = left+(right-left)/2
        else:
            return temp
    return temp

print timeit.timeit("sqrt2(12)", number=10000, setup='from __main__ import sqrt2')
print timeit.timeit("sqrt(12)", number=10000, setup='from math import sqrt')

它只是简单地获取数字并注意什么时候和整数^2比我们的数字小,什么时候(整数+1)^2比我们的数字大,然后将这两个之间的差距除以2,然后尝试中间的数字,等。这对我来说没问题,但是当我尝试 timeit.timeit 它只是停止,控制台中的光标显示它仍在工作,但没有任何反应

如评论中所述,问题是您在此处陷入无限循环:while str(temp**2)!=str(number):

您的问题是 temp**2float 中,而 numberint。由于您比较了它们的字符串表示形式,因此第一个将是 12.0,第二个将是 12.

您可以在 while 循环中修复条件(使用 str() 看起来确实很奇怪),或者将 float 传递给您的函数。

顺便说一下,您的实施速度很慢。带有浮点数 returns 的快速 运行:

你的:0.461127996445

python的:0.000571012496948