Home > Software engineering >  Numpy rounding issue
Numpy rounding issue

Time:08-05

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)

CodePudding user response:

Check the small print 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'
  • Related