Every float in Python occupies 64 bits and follows the IEEE-754 standard, the same format used in most programming languages, giving about 15-17 significant decimal digits of precision. Because it's binary rather than decimal, many ordinary decimal fractions, like 0.1, can't be stored exactly, which is why float arithmetic accumulates small rounding errors. Special values inf, -inf, and nan represent infinity and 'not a number' results, such as from dividing by zero with floats or taking the square root of a negative number.
1Understanding Floats
Every float in Python occupies 64 bits and follows the IEEE-754 standard, the same format used in most programming languages, giving about 15-17 significant decimal digits of precision. Because it's binary rather than decimal, many ordinary decimal fractions, like 0.1, can't be stored exactly, which is why float arithmetic accumulates small rounding errors. Special values inf, -inf, and nan represent infinity and 'not a number' results, such as from dividing by zero with floats or taking the square root of a negative number.
Never use == to compare two computed floats — use math.isclose() instead, since rounding error means two mathematically equal expressions can differ in their last binary digits.
print(0.1 + 0.2)
print(1.5e3)
print(float("inf") > 10 ** 100)2Practical Example
Here is a real-world application of Floats showing how it is used in production Python code.
import math
a = 0.1 + 0.2
b = 0.3
print(a == b)
print(math.isclose(a, b))3Best Practices
Follow these guidelines when working with Floats:
1. Use the decimal module instead of float for money or anywhere exact decimal arithmetic matters
2. Use math.isclose(a, b) rather than == for float comparisons
3. Check for nan with math.isnan(x) instead of comparing to float('nan') directly, since nan is never equal to anything, including itself
Tip: Never use == to compare two computed floats — use math.isclose() instead, since rounding error means two mathematically equal expressions can differ in their last binary digits.
print(0.1 + 0.2)
print(1.5e3)
print(float("inf") > 10 ** 100)