Are the values 161137531201111100, 1.611375312011111e+17 equal?

Viewed 74

I am trying to manipulate a dataframe. The value of in a list which I use to append a column to the dataframe is 161137531201111100. However, I created a dictionary whose keys are the unique values of this column, and I use this dictionary in further operations. This could used to run perfectly before.

However, after trying this code on another data I had the following error:

KeyError: 1.611375312011111e+17

which means that this value is not the of the dictionary; I tried to trace the code, everything seemed to be okay. However, when I opened the csv file of the dataframe I built I found out that the value that is causing the problem is: 161137531201111000 which is not in the list(and ofc not a key in the dictionary) I used to create this column of dataframe. This seems weird. However, I don't know what is the reason? Is there any reason that a number is saved in another way?

And how can I save it as it is in all phases? Also, why did it change in the csv?

1 Answers

No unfortunately, they are not equal

print(1.611375312011111e+17 == 161137531201111000)` # False.

The problem lies in the way floating numbers are handled by computers, in general, and most programming languages, including Python.

Always use integers (and not "too large") when doing computations if you want exact results.

See Is floating point math broken? for generic explanation that you definitely must know as a programmer, even if it's not specific to Python.

(and be aware that Python tries to do a rather good job at keeping precision on integers, that unfortunately won't work on floating-point numbers).

And just for the sake of "fun" with floating point numbers, 1.611375312011111e+17 is actually equal to the integer 161137531201111104!

print(format (1.611375312011111e+17, ".60g"))      # shows 161137531201111104
print(1.611375312011111e+17 == 161137531201111104) # True

a = dict()
a[1.611375312011111e+17] = "hello"
#print(a[161137531201111100])       # Key error, as in question
print(a[161137531201111104])        # This one shows "hello" properly!
Related