我一直假设numpy 使用一种pairwise-summation,它也确保 - 操作的高精度float32:
import numpy as np
N=17*10**6 # float32-precision no longer enough to hold the whole sum
print(np.ones((N,1),dtype=np.float32).sum(axis=0))
# [17000000.], kind of expected
Run Code Online (Sandbox Code Playgroud)
但是,如果矩阵有多于一列,则看起来好像使用了不同的算法:
print(np.ones((N,2),dtype=np.float32).sum(axis=0))
# [16777216. 16777216.] the error is just to big
print(np.ones((2*N,2),dtype=np.float32).sum(axis=0))
# [16777216. 16777216.] error is bigger
Run Code Online (Sandbox Code Playgroud)
可能sum只是天真地将所有值相加。一个迹象是16777216.f+1.0f=16777216.f,例如:
one = np.array([1.], np.float32)
print(np.array([16777215.], np.float32)+one) # 16777216.
print(np.array([16777216.], np.float32)+one) # 16777216. as well
Run Code Online (Sandbox Code Playgroud)
为什么 numpy 不对多列使用成对求和,并且 numpy 是否可以强制对多列使用成对求和?
我的numpy版本是1.14.2,如果这个起作用的话。
当将 Numba@jit与 Numpy 的float32数据类型一起使用时,我收到“截断”?问题。这在很大程度上是噪音,因为它远远超过了我关心的小数点——大约第七位或第八位——但知道发生了什么以及我是否可以修复它仍然是件好事。
float32顺便说一句,我必须使用数据类型来节省内存!
这是我用作测试的代码:
import numpy as np
from test_numba import test_numba
np.random.seed(seed=1774);
number = 150;
inArray = np.round(np.float32((np.random.rand(number)-.5)*2),4); #set up a float32 with 4 decimal places
numbaGet = test_numba(inArray); #run it through
print("Get:\t"+str(numbaGet)+" Type: "+str(type(numbaGet)));
print("Want:\t"+str(np.mean(inArray))+" Type: "+str(type(np.mean(inArray)))); #compare to expected
Run Code Online (Sandbox Code Playgroud)
结合以下函数
import numpy as np
from numba import jit #, float32
@jit(nopython=True) #nopython=True, nogil=True, parallel=True, cache=True , nogil=True, parallel=True #float32(float32),
def test_numba(inArray):
#outArray = np.float32(np.mean(inArray)); #forcing float32 did not change it …Run Code Online (Sandbox Code Playgroud)