jgklsdjfgkldsfaSDF
jgklsdjfgkldsfaSDF

Reputation: 69

Python 3 numpy uses integer division on matrices and regular division on vectors?

When running the following code:

from platform import python_version
print(python_version())
    
import numpy as np
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
x[1,:] = x[1,:] / 5
print(x)
y = np.array([1,2,3])
y = y / 5
print(y)

I get the following output:

3.8.6
[[1 2 3]
 [0 1 1]
 [7 8 9]]
[0.2 0.4 0.6]

Why does numpy / python use integer division when dividing a row in a matrix by a scalar while dividing a single row using regular division? I thought " / " division in numpy 3 was always regular?

Upvotes: 2

Views: 2606

Answers (2)

Turtlean
Turtlean

Reputation: 579

The trick here is in line:

x[1,:] = x[1,:] / 5

According to numpy documentation of dtype: https://numpy.org/doc/stable/reference/generated/numpy.dtype.html

A numpy array is homogeneous, and contains elements described by a dtype object

So when manually assigning the row, it's taking dtype of x matrix into account, which is of type dtype('int64').

The same will happen to you if you tried to manually assign an element to the y array:

y = np.array([1,2,3])
y[1] = 0.5
print(y)
# this will print array([1, 0, 3])

Why does numpy / python use integer division when dividing a row in a matrix by a scalar while dividing a single row using regular division?

So it's about enforcing the homogenous dtype of the np.array itself rather than dividing a row in a matrix, as shown in the line below:

x[1] / 5
>>> array([0.8, 1. , 1.2])

Upvotes: 0

wwii
wwii

Reputation: 23773

Why does numpy / python use integer division when dividing a row in a matrix by a scalar

It doesn't - the symptom you are seeing is due to the assignment.

>>> x = np.array([[1,2,3],[4,5,6],[7,8,9]])

Dividing by an integer produces an array of floats,

>>> z = x[1,:] / 5
>>> z
array([0.8, 1. , 1.2])

But assigning that array to a slice of an integer array causes the dtype conversion.

>>> x[1,:] = z
>>> x
array([[1, 2, 3],
       [0, 1, 1],
       [7, 8, 9]])
>>> z.dtype
dtype('float64')
>>> x.dtype
dtype('int32')
>>>

This is mentioned in the documentation - Assigning values to indexed arrays

Note that assignments may result in changes if assigning higher types to lower types (like floats to ints) or even exceptions (assigning complex to floats or ints):

Upvotes: 3

Related Questions