Home > Software engineering >  Rounding decimal values to nearest integers in a matrix
Rounding decimal values to nearest integers in a matrix

Time:09-16

There are np.around , np.rint and np.round which are all kinda biased towards the even values, for example, 2.5 becomes 2 and 3.5 becomes 4.

I want to round the array of decimals so that rounding happens consistently. Like anything >=x.5 would be x 1 and anything less than <x.5 would be x.
I can write codes with that logic but are there cool and short pythonic ways to do that?

For example, np.unique(MyArray) looks:

[0.         0.08333334 0.125      0.16666667 0.25       0.33333334
 0.375      0.41666666 0.5        0.58333331 0.625      0.66666669
 0.75       0.83333331 0.875      0.91666669 1.         1.08333337
 1.125      1.16666663 1.25       1.33333337 1.375      1.41666663
 1.5        1.58333337 1.625      1.66666663 1.75       1.83333337
 1.875      1.91666663 2.         2.08333325 2.125      2.16666675
 2.25       2.33333325 2.375      2.41666675 2.5        2.58333325
 2.625      2.66666675 2.75       2.83333325 2.875      2.91666675
 3.         3.08333325 3.125      3.16666675 3.25       3.33333325
 3.375      3.41666675 3.5        3.58333325 3.625      3.66666675
 3.75       3.83333325 3.875      3.91666675 4.         4.08333349
 4.125      4.16666651 4.25       4.33333349 4.375      4.41666651
 4.5        4.58333349 4.625      4.66666651 4.75       4.83333349
 4.875      4.91666651 5.         5.08333349 5.125      5.16666651
 5.25       5.33333349 5.375      5.41666651 5.5        5.58333349
 5.625      5.66666651 5.75       5.83333349 5.875      5.91666651
 6.         6.125      6.25       6.33333349 6.375      6.5
 6.625      6.75       6.83333349 6.875      7.         7.16666651
 7.25       7.33333349 7.375      7.58333349 7.66666651 8.        ]

CodePudding user response:

IIUC, you can use np.where:

m = np.linspace(1, 10, 13)
a = np.where(m - m.astype(int) >=  0.5, np.ceil(m), np.floor(m))

Output:

>>> m
array([ 1.  ,  1.75,  2.5 ,  3.25,  4.  ,  4.75,  5.5 ,  6.25,  7.  ,
        7.75,  8.5 ,  9.25, 10.  ])

>>> a
array([ 1.,  2.,  3.,  3.,  4.,  5.,  6.,  6.,  7.,  8.,  9.,  9., 10.])

CodePudding user response:

@banikr, I think that you can useround built-in function.

Here you can read about it.

  • Related