我想用自动四舍五入将int16数组与float数组相乘,但这失败了:
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我得到:
TypeError:不能通过转换规则“same_kind”将ufunc从dtype('float64')到dtype('int16')的输出相乘
发布于 2017-06-30 14:12:42
2解决这个问题的方法:
您可以通过替换来解决这个
A *= B与
A = (A * B)或
numpy.multiply(A, B, out=A, casting='unsafe')发布于 2016-07-30 18:40:33
您可以使用broadcasting对这两个数组进行乘,并且只取整数部分如下:
In [2]: (A*B).astype(int)
Out[2]: array([ 0, 4, 9, 16])时间限制:
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发布于 2016-07-30 19:18:09
import numpy as np
A = np.float_(A)
A *= B尝尝这个。我认为是不同的数组类型,你会失败。
投射
https://stackoverflow.com/questions/38673531
复制相似问题