Override * = operator in numpy

As I mentioned here and here , it is no longer working 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

Workaround:

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 writing too long for each matrix operation!

How can I override the numpy operator *=for this by default?

Should I subclass something?

+4
source share
2 answers

You can use np.set_numeric_opsto override arithmetic methods of an array:

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)
+6
source

You can create a general function and pass the assigned attribute to it:

def calX(a,b, attr):
    try:
        return getattr(numpy, attr)(a, b, out=a, casting="unsafe")
    except AttributeError:
        raise Exception("Please enter a valid attribute")

Demo:

>>> import numpy
>>> A = numpy.array([1, 2, 3, 4], dtype=numpy.int16)
>>> B = numpy.array([0.5, 2.1, 3, 4], dtype=numpy.float64)
>>> calX(A, B, 'multiply')
array([ 0,  4,  9, 16], dtype=int16)
>>> calX(A, B, 'subtract')
array([ 0,  1,  6, 12], dtype=int16)

: , return .

A = calX(A, B, 'multiply')
+1

Source: https://habr.com/ru/post/1649626/


All Articles