Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy Cannot cast ufunc multiply output from dtype

I'd like to multiply an int16 array but a float array, with auto 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 cast ufunc multiply output from dtype('float64') to dtype('int16') with casting rule 'same_kind'

like image 783
Basj Avatar asked Jul 30 '16 11:07

Basj


3 Answers

2 ways to solve this:

You can solve this by replacing

A *= B

with

A = (A * B)

or with

numpy.multiply(A, B, out=A, casting='unsafe')
like image 88
seralouk Avatar answered Oct 03 '22 12:10

seralouk


You could use broadcasting to multiply the two arrays and take only the integer part as follows:

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

Timing Constraints:

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
like image 38
Nickil Maveli Avatar answered Oct 03 '22 12:10

Nickil Maveli


import numpy as np

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

try this. I think are different array type you get fail.

Cast

like image 38
Ahmet İlgin Avatar answered Oct 03 '22 12:10

Ahmet İlgin