How do you store minus and 3.14?
So far we've only stored positive whole numbers like 0, 1, 2. But what about minus five degrees, a negative balance, or 3.14? How do those become 0s and 1s? There are two clever tricks.
Use the very first switch as a sign
The first idea for negatives is simple.
Take one switch
and use it just for the sign.
If the first slot is 0, positive,
if it's 1, negative.
The rest of the switches show the size.
First slot is the sign, the rest is the size.
Flip just the front
and +5 becomes -5.
Simple, right?
But this way has
a small inconvenience.
You have to handle the sign separately when calculating,
and you even end up with two zeros:
positive zero and negative zero.
Spin the numbers around to make negatives
So the way computers actually use
is a bit cleverer.
Picture a car's odometer.
Go one past 9999
and it rolls over to 0000.
The other way, subtract one from 0
and it rolls to the very last number.
Using this,
they decided to use the top numbers as negatives.
Same bits, but spin around once and it becomes negative.
This trick is called two's complement.
The nice part is,
even adding a negative,
if you just add it normally,
the adder circuit gives the right answer on its own.
You don't need to build subtraction separately.
So that's the way computers chose.
The decimal point floats
Now for decimals like 3.14.
The secret is in the name.
The point isn't fixed,
it floats.
With the same digits,
where you put the point
lets you show big numbers and small ones.
Try moving the point
on the number 314.
Move the point and the same digits become a different value.
Move the point left and it shrinks,
right and it grows.
Because the point floats like this,
you can store anything
from very large numbers
to very small ones the same way.
That's why it's called floating point,
a point that floats.
Split it into sign, size, and place
So how do you store
a floating point in 0s and 1s?
Split the switches into three parts.
The front is the sign (the one we just learned),
the middle is the point's position (how big),
the rest is the actual number.
Store it by splitting the switches into three zones.
With just these three pieces
you can write any number with a floating point
in 0s and 1s.
It's the same idea
as scientific notation.
Like splitting 3.14 into 0.314 times 10.
A computer sometimes doesn't know 0.1 exactly
Let me close
with one fun fact.
Ask a computer for 0.1 plus 0.2,
and sometimes you don't get exactly 0.3.
It's off by a tiny bit.
That's because 0.1
can't be stored
cleanly in 0s and 1s.
To our eyes it's 0.3, but inside the computer a tiny error remains.
Just as we have to write 1 divided by 3
as 0.3333... forever,
0.1 in the world of 0s and 1s
is a number that goes on without end.
So it has to be cut off somewhere,
and a tiny error appears there.
The computer isn't wrong,
it's a limit of storing decimals in 0s and 1s.