Home > Net >  numpy rounds floats in an array to ints, but I don't want that
numpy rounds floats in an array to ints, but I don't want that

Time:08-08

I have the following code

import numpy as np

arr=np.array([[3,2,1],[4,3,1],[3,1,0]])
x=np.array([16,21.7,12.1])

for i in range(len(arr)):
    temp=np.copy(arr)
    temp[:,i]=x

when I execute this instead of making temp=[[3,2,16],[4,3,21.7],[3,1,12.1]] it makes [[3,2,16],[4,3,21],[3,1,12]]. it rounds but I don't want that. I used .astype(), float() etc. but didn't work.

CodePudding user response:

Add dtype=float to arr

arr = np.array([[3, 2, 1], [4, 3, 1], [3, 1, 0]], dtype=float)
...
print(temp)

# [[ 3.   2.  16. ]
#  [ 4.   3.  21.7]
#  [ 3.   1.  12.1]]

CodePudding user response:

Declare the array as a float type

arr=np.array([[3,2,1],[4,3,1],[3,1,0]]).astype(np.float32)

or convert it as you copy it

    temp=np.copy(arr).astype(np.float32)
  • Related