2. Basic Types: Numbers
Floats
You might have noticed that division was the only operator to return a number with a fractional component or decimal, for example #\mathtt{\text{3.0}}# instead of #\mathtt{\text{3}}#. You might think what's the big deal, aren't these numbers the same? In a mathematical sense, yes, but for your computer, no. The difference being that decimals are stored differently in computer memory. We call the datatype that includes decimals #\color{#4271ae} {\mathtt{\text{float}}}#, which is short for floating point number.
Floating point formatThe floating point format is a computer number format that represents a wide dynamic range of real numbers as approximations to support a trade-off between range and precision.
First, let's take a look at the multiple ways of declaring a #\color{#4271ae} {\mathtt{\text{float}}}#.
Declaring a floatThe simplest way to declare a float is to add a fractional component to the desired number, if there's a zero before or after the decimal point you can choose to omit the zero:
>>> 1.0
|
1.0
|
>>> 1.
|
1.0
|
>>> .1
|
0.1
|
Since floats are more complicated to store than integers, there's a limit to the numbers the #\color{#4271ae} {\mathtt{\text{float}}}# type can represent. When you enter a number that's bigger than the maximum (or smaller than the minimum) size #\color{#4271ae} {\mathtt{\text{float}}}# can represent, Python will return #\mathtt{\text{inf}}#, which stands for infinity. #\mathtt{\text{inf}}# is a special #\color{#4271ae} {\mathtt{\text{float}}}# that represents the absolute largest value that #\color{#4271ae} {\mathtt{\text{float}}}# can accomodate.
For example, #1\times 10^{999}# is a number that's too big for the #\color{#4271ae} {\mathtt{\text{float}}}# format.
>>> 1e999
|
inf
|
This is similar for a value like #-1\times 10^{999}#:
>>> -1e999
|
-inf
|
Values that exceed the limits of #\color{#4271ae} {\mathtt{\text{float}}}# can still be used in expressions, but the value that is actually used is truncated to the special #\mathtt{\text{inf}}# value. Which means that all the numbers that too large are equal. This is the same for negative numbers.
>>> 1e999 > 1e998
|
False
|
>>> 1e999 == 1e998
|
True
|
Floats support the same operators that integers do, but when an equation includes a #\color{#4271ae} {\mathtt{\text{float}}}#, it will return a #\color{#4271ae} {\mathtt{\text{float}}}#.
Exactly the same usage:
>>> 1.0 + 1.0
|
2.0
|
When mixing #\color{#4271ae} {\mathtt{\text{float}}}# and #\color{#4271ae} {\mathtt{\text{int}}}# typings in an expression, the expression will always return a #\color{#4271ae} {\mathtt{\text{float}}}#.
>>> 1.0 + 1
|
2.0
|
Or visit omptest.org if jou are taking an OMPT exam.