Python floating point built-in data type

The floating point data type in Python supports a real number. The integer data type supports only integer value and the floating point data type was introduced to support a number with fractions. Any numbers assigned to floating point data type is known as floating point literals.

Link : Floating point literals

**Note the floating point type supported by Python is a ‘double’ type, meaning it occupies 64 bits to represent the real number. The size it occupies to hold the real number is important. And it seems Python uses the IEEE 754 double-precision binary floating-point format to evaluate a real number. We will discuss a bit about this later

Link Python Integer-Built-in data type

Like the integer all the mathematical operation can be performed with floating point type.

>>> 23.45 + 90.89 #addition
114.34
>>> 2.34 * 5.67 #multiplication
13.2678
>>> 235.54 / 5 #division
47.108
>>> 24.244 // 2.0
12.0

In the last division since the dividend is a floating point type the result is still a real number even if the division operator used is a double slash (//). We known that // always return an integer but here it does not.

A more example is given below.

>>> 2.45**3 #cube of 2.45
14.706125000000004 
>>> 30.3 % 3 
0.3000000000000007 #remainder neglect the last '7'

As you can see all the mathematical operations can be performed with the floating point numbers.


Disadvantage of floating point type

As said earlier that the floating point in Python is represented using the IEEE 754 double-precision binary floating-point format. This format has many flaws one such is, it cannot represent an accurate value when the values involve may be as small as 0.3 and no doubt it also cannot represent a very large value accurately.

>>> (1234*0.0001)-0.1234
1.3877787807814457e-17

We expect the output to be 0.0 but it is not!

Consider another example.

12345678.99999-12345678.88888
0.11110999993979931 #we expect 0.11111

In the code above we get the wrong output again.(Try using Google calculator it will also give the same output, seems like Google calculator also has some flaws).

These error shows that we cannot depend on floating point for our mathematical operations(if you do not mind the error then go ahead and use them). For instance, in financial calculation or while calculating the radius of a satellite these errors can give rise to many problems.

To counteract thess errors another data type was introduced in Python, this data type is known as Decimal type. We will see about them in another post.


Subscribe here:




Leave a Reply

Your email address will not be published. Required fields are marked *