2

I understand all of these apart from the last one:

import numpy as np
a = np.array(5).astype('uint16')

a
Out[24]: array(5, dtype=uint16)

-a
Out[25]: 65531

a*1.
Out[26]: 5.0

-(a*1.)
Out[27]: -5.0

0-a*1.
Out[28]: -5.0

-a*1.
Out[29]: 65531.0

type(a*1.)
Out[30]: numpy.float64

In the last line a uint variable is multiplied with a float resulting in a float, so why is the result of -a*1. not -5.0, and how is this different from -(a*1.) and 0-a*1.?

konstanze
  • 511
  • 3
  • 12

2 Answers2

2

-a*1. is (-a)*1., because unary - has a higher precedence than *. For details, look at the excerpts from the Python grammar in the documentation.

Sören
  • 1,803
  • 2
  • 16
  • 23
1

I think it is due to the order of operations: -a*1. is from left to right, but 0-a*1. it is a subtraction (even if it is zero) and the 0- is applied after a*1. (where the type of the object is changed).

3dSpatialUser
  • 2,034
  • 1
  • 9
  • 18