Python Forum

Full Version: Number format
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have 2 columns (colA & colB) which is float type.

When I apply the following python code, the 2 columns shows exactly the same value.
Example: colA = 3940.82 vs colB = 3940.82

test = df.groupby('mycol').sum()
However, when I am trying to apply the following code, the above example show up.

test['colA']!=test['colB']
From what I understand, it is floating point error which the exact value might be colA is 3940.82347834 although it shows 3940.82.

I am using the following rounding to solve the issue but is it actually correct? or is there a correct solution to it?
round(test['colA'],2)!=round(test['colB'],2)
floating point is always an approximation see: https://en.wikipedia.org/wiki/Floating-point_arithmetic
Another common way to compare if 2 floats are "close enough" would be
if abs(test['colA'] - test['colB']) < 0.00001 :
or use a numpy function numpy.isclose()