1

I get an error when triyng to right_shift an array with numpy:

Here is the code:

import numpy as np
a = np.ones((10, 10)) * 64
a.astype("int16")
b = a >> 2

And I get

TypeError: ufunc 'right_shift' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

But according to the docs, it seems to me this should work.

1
  • 2
    Try a = a.astype("int16") Commented May 13, 2021 at 11:05

1 Answer 1

1

The astype method can not operate in place because it casts elements to a different size in the general case. Floats are generally 64 bits, while int16 is clearly 16 bits.

Consequently, the line a.astype("int16") is a no-op.

You can either write it as

a = a.astype("int16")

or merge the last two lines:

b = a.astype("int16") >> 2

In general, however, using astype is code smell. Numpy provides the facilities for allocating arrays of the correct type and value to start with:

a = np.full((10, 10), 64, dtype=np.int16)
b = a >> 2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.