python浮点错误

标签 python loops floating-point

<分区>

我在使用 Python 时遇到了一个带有浮点错误的问题。我认为在这里提及它可能会有用。

我有一个以 5000Hz 频率记录数据的外部采样系统。为了获得时间戳,我采用初始时间,然后添加 (1.0/5000) 以获得连续样本的时间戳。我很快注意到当前时间 (time.time()) 在使用循环时偏离了计算时间。只是做简单的计算,没有明显的漂移 - 一些代码:

start_time = time.time()
start_time_test = start_time
#get 512 samples - takes 512*1.0/5000 seconds
for i in arange(512):
   start_time = start_time + (1.0/5000) #5khz

 start_time_test = start_time_test + 512*(1.0/5000)
 print time.time() - start_time_test #no drift
 print time.time() - start_time # drifts
 print start_time_test - start_time # constant increment

现在 start_time_test 和 start_time 之间的差异不是微不足道的 - 每 block 512 大约是 1.69e-5,很快开始累加。我很惊讶浮点错误很快就在这里发挥作用。我将在这里研究使用十进制包来限制错误。

这种级别的浮点错误是可以预期的吗? - 请注意我可能会做一些愚蠢的事情,这不是浮点错误。

最佳答案

a=time.time()
(a+1/5000.0)-a
#0.00020003318786621094
1/5000.0
#0.0002
1331918373+1/5000.0-1331918373
#0.00020003318786621094

时间 float 远大于 1/5000,因此当您添加 10^9+2^-4 时,2^-4 部分会失去精度。

关于python浮点错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9741537/

相关文章:

javascript - 函数和 if else 语句不起作用

algorithm - acosf() 的精确矢量化实现

python - 浮点计算调试

python - 如何在 Flask 中设置响应 header ?

python - 比较 Polars 中的 2 个表并根据该比较选择一个值

Python Gensim : how to calculate document similarity using the LDA model?

c - 取数字并将其存储在C中的 vector 中

python - 抓取 PyQt Python ui 文件中的所有 QPushButton

python - 使用欧拉方法求解微分方程组

Python - ast - 如何找到第一个函数