Home > Enterprise >  numpy: multiply uint16 ndarray by scalar
numpy: multiply uint16 ndarray by scalar

Time:12-05

I have a ndarray 'a' of dtype uint16.

I would like to multiply all entries by a scalar, let's say 2.

The max value for uint16 is 65535. Let's assume some entries of a are greater than 65535/2.

Because of numerical issues, these values will become small values after applying the multiplication

For example, if a is:

1, 1
1, 32867

then a*2 will be:

2, 2
2, 198

This makes sense, but the behavior I would like to enforce is to have 65535 as the "max ceiling", i.e.

x = x*2 if x*2<65535 else 65535

and a*2:

2, 2,
2, 65535

Does numpy support this?

note: I would like the resulting array also to be of dtype uint16

CodePudding user response:

I think the only way is to cast the array to a bigger data type and then clip the values before casting it back to uint16.

For example:

import numpy as np

a = np.array([*stuff], dtype=np.uint16)
res = np.clip(a.astype(np.uint32) * 2, 0, 65535).astype(np.uint16)
  • Related