Search code examples
pythonuint

uint: Why is -(a*b) different from -a*b


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.?


Solution

  • -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.