Reputation: 223
I have some data which looks like this :
353: 340122810048577428
354: 363117512048110005
355: 387632532919029223
356: 413766180933342362
357: 441622981929358437
358: 471314064268398780
359: 502957566506000020
360: 536679070310691121
361: 572612058898037559
362: 610898403751884101
363: 651688879997206959
I am trying to find which index is divisible by 1 million.
index = my_data[:,0]
values = my_data[:,1]
k = 0
for i in values:
k += 1
if i % 1000000 == 0 :
print i
break
print k-1
For this code I am getting output as :
5.02957566506e+17
359
But the value at index 359 is 502957566506000020 for which the last 6 digits are not zero . What mistake am I making here ?
Upvotes: 1
Views: 2257
Reputation: 1613
This type of ambiguity is caused when you use floats. To make the calculation precise you should convert them to long or int and then go ahead. Assuming that you are reading this data from file.
f = open('data.csv')
my_data = []
for line in f:
a = line.split(':')
my_data+=[[int(a[0]), int(a[1])]]
for i in my_data:
if i[1] % 1000000 == 0 :
print i
break
Upvotes: 1
Reputation: 11
You're using floating-point numbers with limited precision. Check this:
>>> 502957566506000020 % 1000000
20
>>> float(502957566506000020)
5.02957566506e+17
>>> 502957566506000020.0
5.02957566506e+17
>>> float(502957566506000020) % 1000000
0.0
>>> 502957566506000020.0 % 1000000
0.0
>>> int(502957566506000020.0)
502957566506000000
Floating-point numbers have a limited precision. So, 502957566506000020 is not exactly representable as a floating point number.
Please read: https://docs.python.org/3/tutorial/floatingpoint.html
Upvotes: 1
Reputation:
Don't use index variables like i
in Python. We are in the 21st century.
s = """353: 340122810048577428
354: 363117512048110005
355: 387632532919029223
356: 413766180933342362
357: 441622981929358437
358: 471314064268398780
359: 502957566506000020
360: 536679070310691121
361: 572612058898037559
362: 610898403751884101
363: 651688879997206959"""
for line in s.split("\n"):
k, v = line.split(":")
if int(v.strip()) % 1000000 == 0:
print(k)
Output: Nothing.
Upvotes: 2