Multiply int and float numeric arrays

I would like to multiply an array int16, but an array floatwith automatic rounding, but this fails:

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

I get:

TypeError: cannot output ufunc multiply the output from dtype ('float64') by dtype ('int16') with the casting rule 'same_kind'

+3
source share
3 answers

You can use broadcastingto multiply two arrays and take only the integer part as follows:

In [2]: (A*B).astype(int)
Out[2]: array([ 0,  4,  9, 16])

Dates:

In [8]: %timeit (A*B).astype(int)
1000000 loops, best of 3: 1.65 µs per loop

In [9]: %timeit np.multiply(A, B, out=A, casting='unsafe')
100000 loops, best of 3: 2.01 µs per loop
+2
source
import numpy as np

A = np.float_(A)
A *= B

try it. I think this is another type of array that you fail.

Cast

+2
source

2 ways to solve this problem:

You can solve this problem by replacing

A *= B

with

A = (A * B)

or

numpy.multiply(A, B, out=A, casting='unsafe')
+1
source

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


All Articles