我在我的函数中使用numpy.vectorize()
,以便将该函数应用于数组,它工作得很好:
X = [-10000, -1000, -100, -10, -1, 0, 1, 10, 100, 1000, 10000]
def softplus(x):
return np.logaddexp(1.0,x)
y=numpy.vectorize(softplus)
问题是我想在结果列表上使用 numpy.around()
将小数点四舍五入到四位,但它不会影响 print
结果。
result = y(X)
print(numpy.around(result, decimals=4))
输出
[ 1.00000000e+00 1.00000000e+00 1.00000000e+00 1.00000000e+00 ...]
最佳答案
这里不需要矢量化
,因为np.logaddexp
已经是一个向量化函数(np.around
也是如此)。但是向量化
给出了正确的结果:
>>> np.logaddexp(1.0, X)
array([ 1.00000000e+00, 1.00000000e+00, 1.00000000e+00,
1.00001670e+00, 1.12692801e+00, 1.31326169e+00,
1.69314718e+00, 1.00001234e+01, 1.00000000e+02,
1.00000000e+03, 1.00000000e+04])
np.around
也能正确舍入结果:
>>> np.around(np.loagaddexp(1.0, X))
array([ 1.00000000e+00, 1.00000000e+00, 1.00000000e+00,
1.00000000e+00, 1.12690000e+00, 1.31330000e+00,
1.69310000e+00, 1.00001000e+01, 1.00000000e+02,
1.00000000e+03, 1.00000000e+04])
但是如果您只想显示 4 位小数,则需要使用其他内容,例如 np.array2string
:
>>> print(np.array2string(np.logaddexp(1., X), precision=4))
[ 1.0000e+00 1.0000e+00 1.0000e+00 1.0000e+00 1.1269e+00
1.3133e+00 1.6931e+00 1.0000e+01 1.0000e+02 1.0000e+03
1.0000e+04]
或者,如果您想显示 4
小数,您可以使用自定义格式化程序:
>>> print(np.array2string(np.logaddexp(1., X), formatter={'float': '{:.4f}'.format}))
[1.0000 1.0000 1.0000 1.0000 1.1269 1.3133 1.6931 10.0001 100.0000
1000.0000 10000.0000]
或使用分隔符
:
>>> print(np.array2string(np.logaddexp(1., X),
... formatter={'float': '{:.4f}'.format},
... separator=', '))
[1.0000, 1.0000, 1.0000, 1.0000, 1.1269, 1.3133, 1.6931, 10.0001, 100.0000,
1000.0000, 10000.0000]
关于python - 如何舍入 numpy 矢量化函数返回的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44048829/