只是出于好奇,我一个简单的数字一个数字的算法来求相同值的平方根 20 次(叹息我知道...)
我对所有 20 次运行都得到了相同的结果,但所有执行的运行时间不同。这是预期的观察结果还是我对计时器的编码很差?
def tester(orange):
import timeit
x = orange
step = 1
guess = 0
epsilon = 0.0000000001
start = timeit.default_timer()
while guess ** 2 < x:
guess += step
if guess ** 2 > x:
guess -= step
if step > epsilon:
step = step / 10
else:
break
print("The square root of", x, "is", guess)
stop = timeit.default_timer()
print('Time: ', stop - start)
number = int(input("Enter the number of times that you want to run this test: "))
answer = float(input("Enter a number to find the square root for: "))
while number > 0:
tester(answer)
number -= 1
沧海一幻觉
相关分类