Python language basics 5: floating point numbers
March 8, 2015 Leave a comment
Introduction
In the previous post we took up the integer built-in data type in Python. In this post we’ll continue with how floating point numbers are declared and used in Python.
As a reminder let’s restate that an important characteristic of Python is duck-typing. In practice it means that we don’t need to declare the type of a variable. It also means that you don’t need to look for keywords like “float” or “double” like in Java or C#, they don’t exist in Python.
Floating point numbers
Like most other programming languages Python supports floating point numbers. I’m not even aware of a single serious language out there which doesn’t support this data type. Floating point numbers in Python are signed and are represented as 64 bit double precision numbers. On this page you can read more about the degree of precision of floats in Python – it’s actually the same as how the double data type is supported in C# and Java.
As mentioned in the post on integers referenced above it’s not even possible to declare a variable like…
float x = 4
…in Python, it will give you a compilation error. Also, there’s no distinction between the different types of floating point numbers like “floats” and “doubles”. Here’s a very simple declaration of a float in Python:
d = 7.344
Scientific notation is represented by “e”. The following expression…:
scientific = 4e10 print(scientific)
…means 4 x (10 to the power of 8), i.e. 40000000000.0.
For small numbers we can also use scientific notation:
verysmall = 0.543e-2
…which reads 0.543 times 10 to the power of -2 and gives 0.00543.
We saw in the post on integers how the int constructor can be used to build integers. There’s a similar float constructor which converts other data types to float.
From a string:
f = float("4.56")
From an integer:
f = float(13)
…where f will become 13.0.
You don’t need to worry about converting between integers and floats when working with both types within the same statement. The result will be converted to float automatically so that you don’t run the risk of losing precision. Example:
fres = 13.6 / 4 print(res)
‘res’ will be 3.4 and not 3.
Read all Python-related posts on this blog here.