Coding

What Is a Float in Python? The float Type Explained

A float in Python is the built-in type for numbers with a fractional part, such as 3.14 or -0.5. Python usually stores it as a C double, a 64-bit IEEE 754 binary value, which means many decimal numbers are held as close approximations rather than exact values.

>>> price = 19.99
>>> type(price)
<class 'float'>

How to create a float

Any number literal with a decimal point is a float. So is a literal in scientific notation, even when it looks like a whole number:

a = 3.14        # decimal point
b = 2.0         # still a float, not an int
c = 1e3         # scientific notation: 1000.0
d = 2.5e-4      # 0.00025
e = float("7")  # convert from a string or an int: 7.0

The float() constructor converts an int or a numeric string. The documentation also says it accepts the strings "nan" and "inf", with an optional + or - prefix, for Not a Number and for positive or negative infinity.

Division with / always gives a float, even when both operands are ints. The article on division and floor division in Python covers when you want / and when you want //.

What a float is inside

The Python reference for numeric types says floating-point numbers are usually implemented using double in C. The tutorial chapter on floating-point arithmetic adds the detail: floats are represented in hardware as base 2 (binary) fractions. On most machines the numerator uses the first 53 bits, starting with the most significant bit, and the denominator is a power of two. Almost all platforms map Python floats to IEEE 754 binary64 "double precision" values, which have 53 bits of precision.

Two practical points follow from that. First, a float has a fixed amount of precision, no matter how large or small the number is. Second, a value can be stored exactly only if it is a fraction whose denominator is a power of two. 0.5 is 1/2, so it is exact. 0.1 is 1/10, and 10 is not a power of two, so it is not.

You can ask Python for the exact fraction behind any float with as_integer_ratio(). The documentation says it returns a pair of integers whose ratio is exactly equal to the float, in lowest terms:

>>> (0.5).as_integer_ratio()
(1, 2)
>>> x = 3.14159
>>> x.as_integer_ratio()
(3537115888337719, 1125899906842624)

The second number there is 250. That is the power-of-two denominator the tutorial describes. The method raises OverflowError on infinities and ValueError on NaNs, since neither is a fraction.

Why 0.1 is not exactly 0.1

For 1/10, the closest binary fraction is 3602879701896397 / 2 ** 55. That is close to, but not exactly equal to, one tenth. The tutorial states that the exact number stored in the computer is 0.1000000000000000055511151231257827021181583404541015625. The computer never "sees" 1/10.

Python hides this when it prints. It shows the shortest decimal string that converts back to the same stored value, which has been the behavior since Python 3.1 on most systems. That is why print(0.1) shows 0.1 and not the long number. You can ask for more digits with a format specification:

>>> 1 / 10
0.1
>>> format(0.1, '.17f')
'0.10000000000000001'

The error is tiny, but it accumulates and breaks equality tests. This example is taken from the Python tutorial:

>>> 0.1 + 0.1 + 0.1 == 0.3
False

Nothing is wrong with Python here. The same result appears in any language that uses IEEE 754 doubles. The decimal values you typed were rounded to binary on the way in, and the sum was rounded again.

How to compare floats correctly

Do not use == on the results of float arithmetic. Use math.isclose(), which was added in Python 3.5:

>>> import math
>>> math.isclose(0.1 + 0.1 + 0.1, 0.3)
True

Its signature is math.isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0). Two values count as close when abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol). The default relative tolerance of 1e-09 means the two values agree to about nine decimal digits. You can change it, for example rel_tol=0.05 for a 5% tolerance.

There is one trap. When you compare against 0.0, the relative tolerance is useless, because isclose(x, 0) works out to abs(x) <= rel_tol * abs(x), which is false for every nonzero x. Pass a small positive abs_tol in that case:

math.isclose(1e-12, 0.0, abs_tol=1e-9)   # True
math.isclose(1e-12, 0.0)                 # False

Special values: infinity and NaN

Floats can also represent values that ints cannot. float("inf") is positive infinity, and -float("inf") is negative infinity. math.inf is equivalent to float('inf'), and for negative infinity you write -math.inf. float("nan") is NaN, "not a number".

NaN breaks the usual rule that a value equals itself:

>>> import math
>>> math.nan == math.nan
False
>>> math.isnan(math.nan)
True

So test for NaN with math.isnan(x), never with x == float("nan"). The math.isclose() function follows IEEE rules for these values: NaN is not close to anything, including NaN, and inf and -inf are close only to themselves.

Checking whether a float holds a whole number

The is_integer() method returns True if the float is finite and has an integral value:

>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False

Because of the rounding described above, a result that should be whole may not be. Use it on values that come straight from input or simple arithmetic, and use round() or math.isclose() when the value is the product of a long calculation. The article on how to round numbers in Python explains round() and why round(2.675, 2) gives 2.67.

When a float is the wrong type

Floats suit measurements, ratios and scientific values, where a relative error around the 16th significant digit does not matter. They are a poor fit when the numbers must match exact decimal rules.

  • Money. The tutorial points to the decimal module for use cases that require exact decimal representation, and says it is suitable for accounting applications and high-precision applications. Store amounts as Decimal values, or as integer cents.
  • Exact fractions. The fractions module does arithmetic on rational numbers, so 1/3 can be represented exactly.
  • Counts and IDs. Use int. It has no fractional part to approximate.

When you must add up many floats, math.fsum() is more accurate than a plain running total. The tutorial says it tracks all the "lost digits" as values are added, so the result has only a single rounding. The built-in sum() uses extended precision for intermediate rounding steps, which is better than a hand-written loop but still not as careful as fsum().

If a float gives a surprising result

Check these in order. If an equality test fails, replace == with math.isclose(). If a comparison against zero fails, add an abs_tol. If the printed digits look wrong, print with format(x, '.17f') to see the stored approximation. If you need exact decimal results, move to Decimal before doing the arithmetic, not after, because the rounding error is already in the float by then.

Frequently asked questions

What is the difference between int and float in Python?
An int holds a whole number of any size and is always exact. A float holds a number with a fractional part, such as 2.5, as a binary approximation with 53 bits of precision on almost all platforms. Use int for counts and IDs, and float for measurements where a tiny rounding error is acceptable.
How many digits of precision does a Python float have?
Almost all platforms map Python floats to IEEE 754 binary64 values, which carry 53 bits of precision. The Python documentation describes the stored value as a binary fraction with a numerator of 53 bits and a power of two as the denominator. For the exact limits on your machine, read sys.float_info.
How do I check whether a float is a whole number?
Call the is_integer() method. (-2.0).is_integer() returns True and (3.2).is_integer() returns False. It also returns False for infinity and NaN, because the documentation defines it as true only for finite floats with an integral value.
Is float('nan') equal to itself?
No. math.nan == math.nan is False, and math.isclose() never treats NaN as close to any value, including NaN. Test for it with math.isnan(x).

Sources