The following expression yields the expected result:
In [ 6 ]: 1 + 4
Out[6]: 5
However, the next case may return a somewhat surprising result:
In [ 7 ]: 1 / 4
Out[7]: 0
In [ 8 ]: type( 1 / 4 )
Out[8]: int
Floats
For the last expression to return the generally desired result of 0.25, we must operate on
float objects, which brings us naturally to the next basic data type. Adding a dot to an
integer value, like in 1. or 1.0, causes Python to interpret the object as a float.
Expressions involving a float also return a float object in general:
[ 19 ]
In [ 9 ]: 1. / 4
Out[9]: 0.25
In [ 10 ]: type (1. / 4 )
Out[10]: float
A float is a bit more involved in that the computerized representation of rational or real
numbers is in general not exact and depends on the specific technical approach taken. To
illustrate what this implies, let us define another float object:
In [ 11 ]: b = 0.35
type(b)
Out[11]: float
float objects like this one are always represented internally up to a certain degree of
accuracy only. This becomes evident when adding 0.1 to b:
In [ 12 ]: b + 0.1
Out[12]: 0.44999999999999996
The reason for this is that floats are internally represented in binary format; that is, a
decimal number 0 < n < 1 is represented by a series of the form . For
certain floating-point numbers the binary representation might involve a large number of
elements or might even be an infinite series. However, given a fixed number of bits used
to represent such a number — i.e., a fixed number of terms in the representation series —
inaccuracies are the consequence. Other numbers can be represented perfectly and are
therefore stored exactly even with a finite number of bits available. Consider the following
example:
In [ 13 ]: c = 0.5
c.as_integer_ratio()
Out[13]: (1, 2)
One half, i.e., 0.5, is stored exactly because it has an exact (finite) binary representation as
. However, for b = 0.35 we get something different than the expected rational
number :
In [ 14 ]: b.as_integer_ratio()
Out[14]: (3152519739159347, 9007199254740992)
The precision is dependent on the number of bits used to represent the number. In general,