Pranav Katta
Pranav Katta

Reputation: 35

dividing a row in a matrix using numpy

I came across this strange behavior when dealing with numpy arrays

x = np.array([[0,3,6],
             [1,5,10]])
print(x[1]/3)
x[1]=x[1]/3
print(x[1])

Output is as shown below:

[0.33333333 1.66666667 3.33333333]
[0 1 3]

Why is it different? And how can I assign [0.33333333 1.66666667 3.33333333] to x[1] without rounding off the values?

Upvotes: 0

Views: 320

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 601619

Numpy arrays have fixed types, determined at the time when the array is created. All elements of your original array have type int. The division results in a floating-point array, but when you assign this back to the integer array, the floating point numbers need to be rounded.

To fix this, you should start with a floating-point array right away, e.g.

x = np.array([[0, 3, 6], [1, 5, 10]], dtype=float)

(Adding a decimal point to any of the numbers in the array also works.)

Upvotes: 4

Related Questions