Can someone explain to me why is numpy round acting strange with this exact number rounding:
JavaScript
x
13
13
1
df = pd.DataFrame({'c': [121921117.714999988675115, 445, 22]})
2
df = np.round(df['c'], 8)
3
4
Result:
5
121921117.71499997
6
445.0
7
22.0
8
9
Expected:
10
121921117.71499999
11
445.0
12
22.0
13
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:
JavaScript
1
2
1
df.applymap(round, ndigits=8)
2
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.
JavaScript
1
9
1
>>> import pandas as pd
2
>>> df = pd.DataFrame({'c': [121921117.714999988675115, 445, 22]})
3
>>> df["c"][0]
4
121921117.71499999
5
>>> round(df["c"][0],8)
6
121921117.71499997
7
>>> np.format_float_positional(df["c"][0],8)
8
'121921117.71499999'
9