Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
Last updated: September 12, 2023
Share on:
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

One of the most commonly used data types in Python is float, which represents floating point numbers. Floating point numbers are numbers, positive or negative, that have a decimal place. Float point numbers also include numbers represented using scientific notation, with the character e or E used to indicate a power of 10.

Float is a very important data type as it can represent a wide range of real numbers, from very small numbers to very large numbers.

python-programming-1

Examples of floating point numbers in Python are shown below:

# float numbers
a = 20.0
b = -51.51345
c = 65e7
d = -1.08E12
e = 2E10

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))

Output:

<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
<class 'float'>
python-float-numbers

Additionally, they allow for more accurate calculations compared to data types such as integers, which remove the fractional part of numbers. For instance, with integers, a number such as 3.142 would be represented simply as 3.

However, the float data type would represent the actual number as is, which is 3.142. Therefore, float values are better suited for mathematical calculations as they yield more accurate results.

In that regard, floating point values are widely used in real-world modeling, machine learning, data science, financial and economic analysis, mathematical computations, graphics and visualizations, and scientific and engineering calculations.

Integers vs. Float in Python

Integers are another very popular data type in Python. Unlike floating point numbers, integers do not have a decimal point. Integers are made up of positive whole numbers, negative numbers, and zero, all of which do not have a fractional part.

Integers are useful when we are performing operations that involve whole numbers, such as when counting or indexing. In Python, integer values are denoted as int.

Some integers are shown below:

a = 0
b = 968
c = -14

print(type(a))
print(type(b))
print(type(c))

Output:

<class 'int'>
<class 'int'>
<class 'int'>
python-int-numbers

Some of the differences between integers and floating-point numbers in Python include:

CharacteristicIntegers(int)Floating Point Numbers(float)
RepresentWhole numbers,  their negative counterparts, and zero, all with no decimal place.Real numbers with a decimal point
PrecisionUnlimited precision thus there is no limit to how long or large an int value can be. The only constraint will be the available memory in your system.Have limited precision. The largest float value you can store is about 1.8 x 10308
Memory UsageUses less memory that floatsUse more memory than integer values
Bitwise OperationsExtensively used in bitwise operations Are almost never used in bitwise operations
UsageTypically used in counting, indexing and bitwise operationsExtensively used in measurements, scientific calculations, and most mathematical operations

Different Ways to Make and Use Floats in Python

An easy way to start working with float values in Python is to assign a variable a float value like so:

# assign a variable a float value
a = 3.142

Another way to get float values is to convert integers and numerical strings into float values using the float() constructor. If we pass in an integer or numerical string into float(), it will be converted to a float value as shown below:

number1 = 2524
numString1 = "513.523"
numString2 = "1341"
# Convert to a float and store the float value in a variable
a = float(number1)
print(a)
b = float(numString1);
print(b)
c = float(numString2)
print(c)

Output:

2524.0
513.523
1341.0
int-to-float

In the example above, the integer and strings are converted to float value using float() and then stored in a variable, which is then printed out, showing the resulting float value after conversion.

Another way of getting float values is by performing mathematical calculations such as division, as shown below:

num1 = 20
num2 = 3
result = num1/num2
print("Result of the division as an integer:")
print(int(20/3))
print("Result of the division as a float value:")
print(result)
print(type(result))

Output:

Result of the division as an integer:
6
Result of the division as a float value:
6.666666666666667
<class 'float'>
float-divisions

In the example above, notice that the float value gives us a more accurate answer compared to dividing and getting the result back as an integer.

When working with float numbers in Python, you might encounter some very interesting results because of how float values are represented internally in the computer. Floating-point numbers are represented in computer hardware as base 2 (binary) fractions.

However, most decimal fractions, particularly those with recurring decimals, cannot be represented as an exact binary fraction. As a result, floating point numbers are usually stored as an approximation of the actual value.

To see this practically, consider the float value 0.3. If you assign 0.3 to a variable, internally, it is not going to be stored as exactly 0.3. To see this, we can use the format() function to see how 0.3 is represented internally. format() allows us to display a desired number of significant figures of a value we are working with. In the example below, we are printing out 0.3 to 20 significant figures to see how it is stored internally.

num = 0.3
print("num to 20 significant figures")
print(format(num, '.20f'))
print("Value we stored for num")
print(num)

Output:

num to 20 significant figures
0.29999999999999998890
Value we stored for num
0.3
significant-figures-float

As you can see, the value 0.3 which we assigned to a variable called num, is not stored internally as exactly 0.3. When you print the variable num, you get a rounded value.

Due to this fact, you might get some unexpected results when working with float values. For instance, if you are to do a manual calculation of 0.3 + 0.3 + 0.3, your answer will be 0.9. However, according to Python, that is not the case because internally, it stores binary fraction approximations of the actual value. This can be seen below:

sum = 0.3 + 0.3 + 0.3
answer = 0.9
print("Is sum equal to answer: ")
print(sum == answer)
print("The internal representation of of sum is: ")
print(sum)
print("The answer from manual calculation is: ")
print(answer)

Output:

Is sum equal to answer: 
False
The internal representation of of sum is: 
0.8999999999999999
The answer from manual calculation is: 
0.9
summation-of-floats

Therefore, when working with float values, it is important to keep in mind that Python does not store exact values internally. Instead, it stores approximations of the actual value.

Therefore, when making comparisons between float values, you might want to first round the off to the same number of significant figures. For greater accuracy when working with floating point numbers in Python, consider using the inbuilt decimal module.

Decimal Module in Python

In situations where high accuracy is important and a must-have such as in financial and scientific calculations, using float is not ideal. To guarantee high accuracy when working with floating point numbers, the inbuilt Python module decimal is used.

Unlike float which is stored as binary floating-point representations that are machine-dependent, the decimal module stores floating-point numbers using machine-independent decimal-based representation which offers higher accuracy.

Additionally, the decimal module is able to represent decimal numbers exactly as they are and use them exactly as they are in calculations. It also offers correctly rounded decimal floating point arithmetic.

To start using the decimal module, import it into your Python file as follows:

import decimal

To see the benefit of the decimal module, let us redo the earlier comparison between the sum of 0.3 + 0.3 + 0.3 and the value 0.9. The code to do this is shown below:

import decimal

sum = decimal.Decimal('0.3') + decimal.Decimal('0.3') + decimal.Decimal('0.3')
answer = decimal.Decimal('0.9')
print("Is sum equal to answer: ")
print(sum == answer)
print("The internal representation of sum is: ")
print(sum)
print("The answer from manual calculation is: ")
print(answer)

Output:

Is sum equal to answer: 
True
The internal representation of sum is: 
0.9
The answer from manual calculation is: 
0.9
decimal-module

Therefore, when working with float point numbers and need high accuracy, remember to always use the decimal module.

Common Errors When Working With Floats

A lot of the errors that arise when working with Float in Python stem from not understanding how float point numbers are represented internally by Python. For instance, a value such as 0.3 will not be stored exactly as 0.3. Therefore, you are likely to run into errors if you work float values, assuming that they are stored exactly as is.

Calculation

One common error is the rounding-off error that you’ll encounter when performing mathematical calculations on float values. Since Python can’t represent the actual float values, you’re likely to encounter rounding-off errors where the results may not be what you expect.

Because of errors such as rounding off errors, you’re likely to run into errors when you try to make equality comparisons between floating point values. Exercise a lot of caution when working with floats in Python, and be aware of unexpected outcomes.

A better way to avoid all the errors that may arise as you work with float values is to use the inbuilt decimal module. This way, the outcomes from your floating point number calculations will be more predictable and accurate.

Conclusion

As a programmer working with Python, you are bound to use the float data type. To avoid errors with this data type, it is important to understand how Python represents float numbers internally. Since Python cannot store the actual float numbers, avoid doing exact equality comparisons with float values. Otherwise, you’ll run into errors.

In case you need accurate results in your application, avoid using float values. Instead, use the inbuilt decimal module, which yields accurate floating-point number results and represents them exactly as they are and in a machine-independent manner.

You may also read Python Itertools Functions and Python Try Except.

  • Collins Kariuki
    Author
    Collins Kariuki is a software developer and technical writer for Geekflare. He has over four years experience in software development, a background in Computer Science and has also written for Argot, Daily Nation and the Business Daily Newspaper.
  • Narendra Mohan Mittal
    Editor

    Narendra Mohan Mittal is a Senior Digital Branding Strategist and Content Editor with over 12 years of versatile experience. He holds an M-Tech (Gold Medalist) and B-Tech (Gold Medalist) in Computer Science & Engineering.


    read more
Thanks to our Sponsors
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Monday.com is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.
    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder