2Obe
2Obe

Reputation: 3710

Element of array set as integer instead of float

I have issues setting an element of an array to a float number.

C = [(np.random.randint(-10,10),np.random.randint(-10,10)) for i in range(3)]
C = np.array(C)
C[0,0] = 1.654
print(C[0,0])

1

I wonder why this is not 1.654 but gives me the integer 1 instead.

Upvotes: 0

Views: 57

Answers (2)

alcantula
alcantula

Reputation: 179

Because you use randint which is giving a integer value. Change the code to this for getting the float.

import numpy as np

C = [(float(np.random.randint(-10,10)),float(np.random.randint(-10,10))) for i in range(3)]
C = np.array(C)
C[0,0] = 1.654
print(C[0,0])

Upvotes: 1

2Obe
2Obe

Reputation: 3710

I have the solution.... I have to use the numpy array dtype parameter which says:

dtype : data-type, optional The desired data-type for the array. If not given, then the type will be determined as the minimum type required to hold the objects in the sequence. This argument can only be used to ‘upcast’ the array. For downcasting, use the .astype(t) method.

C = [(np.random.randint(-10,10),np.random.randint(-10,10)) for i in range(3)]
C = np.array(C,dtype='float32')
C[0,0] = 1.654
print(C[0,0])

So clearly, C is of dtype int because this is sufficient to store the random integer values. If I now want to set an element of C to a float value I have to change the dtype of C.

Upvotes: 0

Related Questions