Skip to main content
 首页 » 编程设计

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

2025年05月04日12jiqing9006

所以我尝试编写一个简单的平方根函数。我做了,我想将它与 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 较低以及何时 (integer+1)^2 高于我们的数字,然后将这些 2 之间的差距除以 2,并尝试中间的数字,等等。这对我来说没问题,但是当我尝试 timeit.timeit 时它只是停止,控制台显示光标,它仍在工作,但没有任何反应

请您参考如下方法:

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

您的问题是 temp**2 在 float 中,而 number 是 int。由于您比较了它们的字符串表示形式,例如,第一个是 12.0,第二个是 12。

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

顺便说一下,您的实现速度非常慢。快速运行一个 float 返回:

你的:0.461127996445

python 的:0.000571012496948