为什么在python中查找epsilon的迭代算法几乎需要0秒?

2024-04-19 19:29:00 发布

您现在位置:Python中文网/ 问答频道 /正文

寻找python epsilon(没有任何库)我编码:

import time
start = time.time()
x=1.0

while 1+x/2 != 1.0:
    x/=2.0
print x
print time.time() - start

我得到了结果:

2.22044604925e-16
5.79357147217e-05

我不认为回答一点点时间仅仅是因为有那么快


Tags: import编码time时间startprintwhileepsilon
2条回答

看看^{}模块。它非常适合评估运行时间非常短的代码:

import timeit

def algorithm():
    x=1.0
    while 1+x/2 != 1.0:
        x/=2.0
    #print x  # disabled so i don't get 100,000 prints

timeit.timeit(algorithm, number=100000) # 100,000 times!

输出(对于我):

0.95662535660580161

double-precision binary floating-point format

Significand precision: 53 bits (52 explicitly stored)

如果您添加一个循环计数器,您将看到它只执行了52次。你知道吗

相关问题 更多 >