Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Number format
#1
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)
Reply
#2
floating point is always an approximation see: https://en.wikipedia.org/wiki/Floating-point_arithmetic
Reply
#3
Another common way to compare if 2 floats are "close enough" would be
if abs(test['colA'] - test['colB']) < 0.00001 :
Reply
#4
or use a numpy function numpy.isclose()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Photo How can I use 2 digits format for all the number? plumberpy 6 2,299 Aug-09-2021, 02:16 PM
Last Post: plumberpy
  multiple number format conversion oli_action 4 2,531 Aug-11-2020, 05:10 AM
Last Post: perfringo
  Changing Number Format moby 4 4,997 May-24-2019, 11:04 PM
Last Post: snippsat
  Counting the number of files related to particular format ambush 3 2,876 Nov-05-2018, 08:58 AM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020