4

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)
1
  • 1
    always tag python questions with the generic [python] tag Commented Aug 4, 2022 at 16:49

1 Answer 1

3

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Great, thanks for explaining all of this. I'm focused here on the precision, not so much on the performance, so I've used this function (edited the original post also): df.applymap(round, ndigits=decimals)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.