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 instead of . 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 , 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 .
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 type can represent. When you enter a number that's bigger than the maximum (or smaller than the minimum) size can represent, Python will return , which stands for infinity. is a special that represents the absolute largest value that can accomodate.
For example, is a number that's too big for the format.
>>> 1e999
|
inf
|
This is similar for a value like :
>>> -1e999
|
-inf
|
Values that exceed the limits of can still be used in expressions, but the value that is actually used is truncated to the special 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 , it will return a .
Exactly the same usage:
>>> 1.0 + 1.0
|
2.0
|
When mixing and typings in an expression, the expression will always return a .
>>> 1.0 + 1
|
2.0
|
Or visit omptest.org if jou are taking an OMPT exam.