【发布时间】:2020-03-01 09:12:13
【问题描述】:
当我使用 numpy 对函数进行矢量化时,我得到了一个奇怪的结果。
import numpy as np
def scalar_function(x, y):
""" A function that returns x*y if x<y and x/y otherwise
"""
if x < y :
out = x * y
else:
out = x/y
return out
def vector_function(x, y):
"""
Make it possible to accept vectors as input
"""
v_scalar_function = np.vectorize(scalar_function)
return v_scalar_function(x, y)
我们有
scalar_function(4,3)
# 1.3333333333333333
为什么矢量化版本会给出这种奇怪的输出?
vector_function(np.array([3,4]), np.array([4,3]))
[12 1]
虽然对矢量化版本的调用工作正常:
vector_function(np.array([4,4]), np.array([4,3]))
[1. 1.33333333]
阅读numpy.divide:
注意事项 地板除法运算符 // 在 Python 2.2 中添加了 // 和 / 等效运算符。 / 的默认楼层除法操作可以用 from
__future__导入除法替换为真除法。 在 Python 3.0 中,// 是地板除法运算符和 / 真正的除法运算符。 true_divide(x1, x2) 函数相当于 Python 中的真正除法。
让我觉得这可能是与 python2 相关的遗留问题? 但我使用的是 python 3!
【问题讨论】:
-
文档说“输出类型是通过评估输入的第一个元素来确定的,除非它被指定”。我的猜测是,对于整个返回数组,第一个实例中整数类型的乘法会自动转换为
int类型,而除法,即使是 4/4 的结果也会自动转换为浮点数 -
顺便说一句;我看到你主要习惯于 R。只要检查一下你是否知道
vectorize是一个便利函数,它不会增加 pythonfor循环的速度,应该尽可能避免