Sub topic 4
Downcasting floats and what precision you give up
This chapter assumes you can read float64 and float32 as dtype names, and that you have used pd.to_numeric to downcast integers. Floats follow the same idea, with one difference. Integer downcasting is exact when the values fit the range. Float downcasting usually loses digits.
What float32 keeps and drops
A float stores a sign, an exponent, and a fixed number of significant bits. float64 uses 8 bytes and keeps about 15 decimal digits. float32 uses 4 bytes and keeps about 6 to 7. You can read this from NumPy.
import numpy as np
for t in (np.float16, np.float32, np.float64):
info = np.finfo(t)
print(t.__name__, info.bits // 8, info.precision, info.max)| dtype | bytes | reliable digits | largest value |
|---|---|---|---|
| float16 | 2 | 3 | 65504 |
| float32 | 4 | 6 | about 3.4e38 |
| float64 | 8 | 15 | about 1.8e308 |
Downcasting a column
pd.to_numeric(..., downcast="float") converts a column to the smallest float dtype it will use. That is float32 at minimum, because pandas does not pick float16. The memory for this column halves.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
s = pd.Series(rng.random(100_000))
small = pd.to_numeric(s, downcast="float")
print(s.dtype, small.dtype)
print(s.memory_usage(index=False), small.memory_usage(index=False))
abs_err = (s - small).abs()
print(abs_err.max())
print((abs_err / s).max())The memory goes from 800,000 bytes to 400,000. The relative error stays below about 6e-8, which is the precision limit of float32. For scores, ratings, or sensor readings with noise larger than that, the loss does not matter.
When float32 is the wrong choice
The float32 mantissa has 24 bits. Whole numbers are exact only up to 2**24, which is 16,777,216. Above that, neighbouring integers collapse together.
import pandas as pd
ids = pd.Series([16_777_216.0, 16_777_217.0])
print(ids.astype("float32").tolist())This prints [16777216.0, 16777216.0]. Two different values became one. A column of large identifiers stored as floats, such as order numbers, is a common case where this happens.
Other cases to watch:
- Money and exact decimals. Neither
float32norfloat64stores 0.1 exactly.float32makes the error roughly a billion times larger. Use integer cents ordecimalfor money. - Sums and means over many rows. Each addition rounds at 6 to 7 digits, so errors can build up. If a column feeds large aggregates, keep
float64or check the result against afloat64run. - Equality tests. A value read from
float32and compared to a Python float such as0.1will not match. Usenp.iscloseor compare after casting. - Very small or very large magnitudes. Values beyond about 3.4e38 become
infinfloat32. With a manualastype("float16"), anything above 65504 does the same.
The last bullet is why downcast="float" stops at float32. A manual astype("float16") saves another 2 bytes per value. It is only safe for coarse data, such as values in a small range where three digits are enough. Check the range first.
Missing values
NaN is a float value in every float dtype, so downcasting does not change how missing data behaves. Integer columns with missing values are already float64. Converting those to float32 loses exactness above 2**24, as shown above. Consider the nullable Int32 dtype if the column holds whole numbers.
A quick check
Measure the worst-case error on your own data before you decide.
import numpy as np
import pandas as pd
def float32_is_safe(col, rtol=1e-6):
converted = col.astype("float32")
if np.isinf(converted).any() and not np.isinf(col).any():
return False
return np.allclose(col, converted, rtol=rtol, equal_nan=True)
values = pd.Series([0.1, 2.5, 1e6, np.nan])
print(float32_is_safe(values))The function rejects a column when conversion overflows to inf. Otherwise it applies a relative tolerance you choose. Pick rtol from how accurate your analysis needs to be, not from what happens to pass.
Exercise
A column holds invoice totals in dollars, such as 1249.99, and you plan to sum them across 5 million rows. Should you downcast it to float32? Give two reasons for your answer.
Show answer
No. First, float32 keeps only 6 to 7 significant digits, so a total like 1249.99 is stored with a small rounding error. Second, the rounding error accumulates when you add millions of rows, so the sum can drift from the true value. Keep float64, or store the amounts as integer cents.