Overview
Dear roommate, "Is there such a thing as minus zero?"
Mirori: "Huh? No, right? Zero is neither negative nor positive."
Python: "There is, though."
Here we go. Playing with programming, this is the most fun part. It's time for our daily dose of Python.
There's a Minus in float
Type Zero
See? You can attach a minus to float
's 0.0
.
python -V
# Python 3.10.12
python -c 'print(0.0 * -1)'
# -0.0
python -c 'print(0 / -1)'
# -0.0
-0.0
is equivalent to 0.0
, but not the same.
python -c 'print(-0.0 == 0.0)'
# True
python -c 'print(-0.0 is 0.0)'
# SyntaxWarning: "is" with a literal. Did you mean "=="?
# False
is
is usually used for things like bool
or None
, so Python gives us a warning. But in this case, ==
and is
give different results, so there's a reason to use them differently, right, Python?
Conversely, if you want to turn -0.0
into 0.0
, you can just add 0.0
or multiply by -0.0
. This is the same as with regular integers.
python -c 'print(-0.0 + 0.0)'
0.0
python -c 'print(-0.0 * -0.0)'
0.0
Why?
float
, or floating-point numbers, are made up of the following structure:
- Sign (positive or negative)
- Mantissa
- Exponent
-12.34 = -, 1.234, 10**1 = sign, mantissa, 10**exponent
So, when you do a calculation that results in a minus sign, the minus stays put. Hmm. This is the most fun part...