Python floating point built-in data type

The floating point data type in Python supports a real number that is any kind of number a number with fraction or without fraction.The integer data type supports only integer value and this floating point was introduced to support a number with fraction since we always need a number with decimal point value.


**Note the floating point type supported by Python is a ‘double’ type meaning it occupy 64 bits to represent the real number.The size it occupy 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

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

>>> 23.45 + 90.89 #addition
>>> 2.34 * 5.67 #multiplicationa
>>> 235.54 / 5 #division
>>> 24.244 // 2.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 (//).

A more example is given below.

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

As you can see all the mathematical operation can be performed with floating point number too.

Disadvantage of floating point type

I have earlier said that the floating point in Python is represented using the IEEE 754 double-precision binary floating-point format.And this format has many flaws one such is it cannot represent an accurate value in mathematical operation sometimes even if the values involve may only be as small as 0.3 and no doubt it also cannot represent a very large value accurately.

>>> (1234*0.0001)-0.1234

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

Consider another example.

0.11110999993979931 #we expect 0.11111

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

These error shows that we cannot depend on floating point for our mathematical operation(if you do not mind the error then go ahead).For instance in financial calculation or while calculating the radius of a satellite these errors can give rise to many problems.So to counteract this another type is introduced in Python known as Decimal type.We will see about them in another post.

Leave a Reply

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