Mailing List Archive

Re: Understanding the working mechanis of python unary arithmetic operators.
On Saturday, 2 October 2021 at 13:48:39 UTC+1, hongy...@gmail.com wrote:
> On Saturday, October 2, 2021 at 4:59:54 PM UTC+8, ju...@diegidio.name wrote:
> > On Saturday, 2 October 2021 at 10:34:27 UTC+2, hongy...@gmail.com wrote:
> > > See the following testings:
> > >
> > > In [24]: a=3.1415926535897932384626433832795028841971
> > > In [27]: -a
> > > Out[27]: -3.141592653589793
> > You've never heard of floating-point? Double precision has 53 significant bits of mantissa, corresponding approximately to 16 decimal digits.
> > <https://en.wikipedia.org/wiki/Double-precision_floating-point_format#IEEE_754_double-precision_binary_floating-point_format:_binary64>
> > > In [17]: ~-+1
> > > Out[17]: 0
> > << The unary ~ (invert) operator yields the bitwise inversion of its integer argument. The bitwise inversion of x is defined as -(x+1). It only applies to integral numbers or to custom objects that override the __invert__() special method. >>
> > <https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations>
> > > I'm very puzzled by these operators. Any hints will be highly appreciated.
> > Try and read the proverbial manual: that's truly a fundamental skill...
> Thank you for your explanation. Then what about the following questions?:
>
> 1. Should `+' and `-' be classified as binary operators or unary operators?

Both. See sections 6.6 and 6.7 of the documentation at
https://docs.python.org/3/reference/expressions.html

> As we all know, `a + b', and `a - b' are the normal ways we do basic arithmetic operations.

Really? Don't you ever write something like "x = -y"?
Or do you habitually write "x = 0 - y" or "x = 0.0 - y"?

> 2. See the following testings:
>
> In [20]: bool(int(True))
int(True) -> 1
bool(1) -> True
> Out[20]: True
>
> In [21]: bool(~int(True))
int(True) -> 1
~1 -> -2
bool(-2) -> True
> Out[21]: True
>
> In [22]: bool(~~int(True))
int(True) -> 1
~1 -> -2 # these two operations
~(-2) -> 1 # cancel each other out
bool(1) -> True
> Out[22]: True
>
> In [23]: bool(~~~int(True))
Because two consecutive bit-inversions cancel each other out;
this is just a complicated re-statement of operation [21], above
> Out[23]: True
>
> In [24]: bool(int(False))
int(False) -> 0
bool(0) -> False
> Out[24]: False
>
> In [25]: bool(~int(False))
int(False) -> 0
~0 -> -1
bool(-1) -> True
> Out[25]: True
>
> In [26]: bool(~~int(False))
Again, two consecutive inversions cancel each other out
so this is just an over-complicated re-statement of [24]
> Out[26]: False
>
> In [27]: bool(~~~int(False))
Likewise, this is the equivalent of re-stating [25]
> Out[27]: True
>
> Why can’t/shouldn't we get something similar results for both `True' and `False' in the above testings?

Sorry, I can't parse that.
--
https://mail.python.org/mailman/listinfo/python-list