Skip to content
Advertisement

Numpy rounding issue

Can someone explain to me why is numpy round acting strange with this exact number rounding:

df = pd.DataFrame({'c': [121921117.714999988675115, 445, 22]})
df = np.round(df['c'], 8)

Result:
121921117.71499997
445.0
22.0

Expected:
121921117.71499999
445.0
22.0

It’s obvious that the first number is not rounded well, any ideas?

EDIT: Since I’m focused here on the precision, not so much on the performance, I’ve used python round function to solve this problem:

df.applymap(round, ndigits=8)

Advertisement

Answer

Check the small print 2 in the documentation of round aka around. The short answer is that round “uses a fast but sometimes inexact algorithm” and to use format_float_positional if you want to see the correct result.

enter image description here

>>> import pandas as pd
>>> df = pd.DataFrame({'c': [121921117.714999988675115, 445, 22]})
>>> df["c"][0]
121921117.71499999
>>> round(df["c"][0],8)
121921117.71499997
>>> np.format_float_positional(df["c"][0],8)
'121921117.71499999'
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement