在numpy中重新定义* =运算符 [英] Redefine *= operator in numpy
本文介绍了在numpy中重新定义* =运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如此处提到和
As mentioned here and here, this doesn't work anymore in numpy 1.7+ :
import numpy
A = numpy.array([1, 2, 3, 4], dtype=numpy.int16)
B = numpy.array([0.5, 2.1, 3, 4], dtype=numpy.float64)
A *= B
一种解决方法是:
def mult(a,b):
numpy.multiply(a, b, out=a, casting="unsafe")
def add(a,b):
numpy.add(a, b, out=a, casting="unsafe")
mult(A,B)
但这对于每个矩阵运算来说太长了!
but that's way too long to write for each matrix operation!
默认情况下如何覆盖numpy *=
运算符以执行此操作?
How can override the numpy *=
operator to do this by default?
我应该继承某些东西吗?
Should I subclass something?
推荐答案
您可以使用np.set_numeric_ops
覆盖数组算术方法:
You can use np.set_numeric_ops
to override array arithmetic methods:
import numpy as np
def unsafe_multiply(a, b, out=None):
return np.multiply(a, b, out=out, casting="unsafe")
np.set_numeric_ops(multiply=unsafe_multiply)
A = np.array([1, 2, 3, 4], dtype=np.int16)
B = np.array([0.5, 2.1, 3, 4], dtype=np.float64)
A *= B
print(repr(A))
# array([ 0, 4, 9, 16], dtype=int16)
这篇关于在numpy中重新定义* =运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文