[SOLVED] Python numpy array values get rounded after boolean indexing

Issue

I want to apply calculation only for those values that are higher than threshold. After doing it with boolean indexing, values get rounded. How to prevent it?

starting_score = 1
threshold = 5
x = np.array([0,1,2,3,4,5,6,7,8,9,10])
gt_idx = x > threshold
le_idx = x <= threshold
decay = math.log(2) / 10
y = starting_score * np.exp(-decay * x)
x[gt_idx] = starting_score * np.exp(-decay * x[gt_idx])

y
array([1.        , 0.93303299, 0.87055056, 0.8122524 , 0.75785828,
       0.70710678, 0.65975396, 0.61557221, 0.57434918, 0.53588673,
       0.5       ])


x
array([0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0])

when applied to full array, I get correct y array.
when applied to part of x, values get selected properly, but rounded to 0

My expected output is

 array([0, 1, 2, 3, 4, 5, 0.65975396, 0.61557221, 0.57434918, 0.53588673, 0.5])

Solution

It is considered np.int32 as default type for when you create a NumPy array with integers as x. For getting other types in the results you have two ways:

# np.float32 or np.float64
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=np.float64)  # way 1
x = x.astype(np.float64)                                            # way 2

such operation is not needed for y because in is multiplied by a float type value i.e. np.exp(-decay * x), so it became to float types.

Answered By – Ali_Sh

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *