5

我有两台计算机,python 2.7.2(win32 上的 MSC v.1500 32 位(Intel)])和 numpy 1.6.1。但

numpy.mean(data)

返回

1.13595094681 on my old computer 

1.13595104218 on my new computer

在哪里

Data = [ 0.20227873 -0.02738848  0.59413314  0.88547146  1.26513398  1.21090782
1.62445402  1.80423951  1.58545554  1.26801944  1.22551131  1.16882968
1.19972098  1.41940248  1.75620842  1.28139281  0.91190684  0.83705413
1.19861531  1.30767155]

在这两种情况下

s=0
for n in data[:20]:
  s+=n
print s/20

1.1359509334

谁能解释为什么以及如何避免?

麦兹

4

2 回答 2

3

如果您想避免两者之间的任何差异,请明确将它们设为 32 位或 64 位浮点数组。NumPy 使用其他几个可能是 32 位或 64 位的库。请注意,您的打印语句中也可能发生舍入:

>>> import numpy as np
>>> a = [0.20227873, -0.02738848,  0.59413314,  0.88547146,  1.26513398,
         1.21090782, 1.62445402,  1.80423951,  1.58545554,  1.26801944,
         1.22551131,  1.16882968, 1.19972098,  1.41940248,  1.75620842,
         1.28139281,  0.91190684,  0.83705413, 1.19861531,  1.30767155]
>>> x32 = np.array(a, np.float32)
>>> x64 = np.array(a, np.float64)
>>> x32.mean()
1.135951042175293
>>> x64.mean()
1.1359509335
>>> print x32.mean()
1.13595104218
>>> print x64.mean()
1.1359509335

需要注意的另一点是,如果您有多线程的较低级别的库(例如,atlas、lapack),那么对于大型数组,由于可能的操作顺序和浮点精度的可变,您的结果可能会有所不同.

此外,您处于 32 位数字的精度极限:

>>> x32.sum()
22.719021
>>> np.array(sorted(x32)).sum()
22.719019
于 2012-11-16T21:19:19.520 回答
0

This is happening because you have Float32 arrays (single precision). With single precision, the operations are only accurate to 6 decimal place. Hence your results are the same up to the 6th decimal place (after the decimal point, rounding the last digit), but they are not accurate after that. Different architectures/machines/compilers will yield the different results after that. If you want the same results you should use higher precision arrays (e.g. Float64).

于 2012-11-17T04:40:34.503 回答