【发布时间】:2016-05-19 15:32:46
【问题描述】:
我从 numpy(版本 1.10.4)看到了一些非常令人惊讶的行为。请参阅以下带有输出的代码:
import numpy as np
a = np.random.rand()
b = np.random.rand(1)[0]
print('a: ',a)
print('b:', b)
print('type(a): ', type(a))
print('type(a): ', type(b))
print('round(a):', round(a))
print('round(b):', round(b))
print('\n')
%timeit round(a)
%timeit round(b)
%timeit int(round(b))
a: 0.4991662851604657
b: 0.301059130742
type(a): <class 'float'>
type(a): <class 'numpy.float64'>
round(a): 0
round(b): 0.0
The slowest run took 7.49 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 232 ns per loop
The slowest run took 13.84 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.19 µs per loop
The slowest run took 6.54 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.37 µs per loop
np.random.rand 似乎在两种非常相似的情况下返回不同的数字类型。
这让我很生气,因为我开始依赖 Python 的 round 的行为,它默认返回 int。但是,如果round 的输入是numpy.float64,它会返回float,我猜是因为numpy.round 确实如此。依赖round 的行为突然变得相当危险。
round 在 float 与 numpy.float64 上的表现也有很大不同,以至于它对我的库产生了明显的影响。
性能问题是一个错误,还是 numpy 开销真的那戏剧性,即使对于标量 floats,还是这里的基准测试工作方式存在问题?如何从numpy.float64s 快速舍入到int 性能?
最后,为什么rand() 返回的类型与rand(1)[0] 不同?
【问题讨论】:
标签: python performance numpy types rounding