Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying a np.int8 array with 127 yields different numpy array types depending on platform

The following code:

>>> import numpy as np
>>> np.arange(2).astype(np.int8) * 127

produces for numpy 1.13.3

# On Windows
array([0, 127], dtype=int16)
# On Linux
array([0, 127], dtype=int8)

However, if I change the 127 to a 126, both return a np.int8 array. And if I change the 127 to a 128 both return a np.int16 array.

Questions:

  • Is this expected behaviour?
  • Why is it different for the two platforms for this one case?
like image 630
NOhs Avatar asked Dec 06 '17 19:12

NOhs


People also ask

How do you multiply the two NumPy arrays with each other?

multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.

How does NumPy multiply work?

What does Numpy Multiply Function do? The numpy multiply function calculates the product between the two numpy arrays. It calculates the product between the two arrays, say x1 and x2, element-wise.

How do you multiply a list in NumPy?

We can use numpy. prod() from import numpy to get the multiplication of all the numbers in the list.

How do you perform matrix multiplication on the NumPy arrays A and B?

If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred. If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred. If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.


1 Answers

This is due to NumPy issue 5917. A < instead of <= caused np.can_cast(127, np.int8) to be False, so NumPy used a too-large dtype for 127. The OS-dependence is because C longs have a different size on Linux and Windows, and some NumPy code paths depend on the size of a C long.

A fix has been released in NumPy 1.14.0. Once you update to at least NumPy 1.14.0, you should see a dtype of int8 on all platforms.

like image 157
user2357112 supports Monica Avatar answered Sep 20 '22 04:09

user2357112 supports Monica