NumPy中的math.remainder()
函数等效于什么?基本上,我想为NumPy数组y = x - np.around(x)
计算x
。 (重要的是y
的所有元素都绝对不超过1/2)。在查看NumPy文档时,np.fmod
和np.remainder
都不起作用。
很显然,我曾考虑过编写x - np.around(x)
,但恐怕对于大的x
减法会产生浮点错误。例如:
import numpy as np
a = np.arange(1000) * 1e-9
x = a / 1e-9
y = x - np.around(x)
应该产生全零向量y
,但实际上会出现一些错误(如果将数组的大小从1000增加到10000,错误会变得更大)。
我问这个问题的原因是要弄清楚是否有为此目的直接调用C数学库remainder
(如math.remainder
那样的NumPy函数)以最小化浮动点错误。
答案 0 :(得分:0)
我不认为当前存在numpy
。也就是说,自动numpy.vectorize
调用对我来说是正确的事,例如:
import math
import numpy as np
ieee_remainder = np.vectorize(math.remainder)
ieee_remainder(np.arange(5), 5)
这很好地广播了参数,给出了:
array([ 0., 1., 2., -2., -1.])
这可能就是您想要的。
性能比本地实现慢大约10倍。给定一万个元素阵列,我的笔记本电脑大约需要以下时间:
ieee_remainder
的1200 µs numpy.fmod
持续80 µs 鉴于glibc's remainder
implementation的复杂性,我惊讶的是它是如此之快。