0

I am trying to convert a number to list, but the last few digits don't match. Can someone explain why this is happening.

num = 6145390195186705544
lista = []
while num !=0:

    lista.append(num%10)
    num = int(num/10)

print(lista[::-1])

[6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 6, 6, 2, 4, 6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 6, 6, 2, 4, 6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 6, 6, 2, 4, 6, 1, 4, 5, 3, 9, 0, 1, 9, 5, 1, 8, 6, 7, 0, 6, 6, 2, 4]

I am using python3

Sukruth
  • 1
  • 1
  • 6
    You need `num//10`, otherwise it is a floating point operation. – MisterMiyagi Oct 04 '22 at 17:03
  • Does this answer your question? https://stackoverflow.com/questions/1282945/why-does-integer-division-yield-a-float-instead-of-another-integer – MisterMiyagi Oct 04 '22 at 17:07
  • Following the comment of @MisterMiyagi , double precision floating point numbers have only 15 to 16 significant digits, so incorrect results will occur. – Mechanic Pig Oct 04 '22 at 17:10
  • 1
    `num/10` will result in a `float` before you use `int` on it, but for large numbers, `float` will not be able to handle this with exact precision. Use *integer division*, i.e. `//` – juanpa.arrivillaga Oct 04 '22 at 17:49

1 Answers1

1

[PEP 238] says: The current division (/) operator has an ambiguous meaning for numerical arguments: it returns the floor of the mathematical result of division if the arguments are ints or longs, but it returns a reasonable approximation of the division result if the arguments are floats or complex. This makes expressions expecting float or complex results error-prone when integers are not expected but possible as inputs.

This should work:

num = 6145390195186705544
lista = []
while num != 0:
    lista.append(num % 10)
    num = num // 10

print(lista[::-1])
  • Code-only answers that don't explain what's wrong and why the fix works are not great answers; please add an explanation, so the OP knows *why* it went wrong and can avoid the problem in the future. – ShadowRanger Oct 04 '22 at 17:29
  • https://peps.python.org/pep-0238/ – Bekhruz Rakhmonov Oct 04 '22 at 17:48
  • This doesn't really explain anything – juanpa.arrivillaga Oct 04 '22 at 17:50
  • The current division (/) operator has an ambiguous meaning for numerical arguments: it returns the floor of the mathematical result of division if the arguments are ints or longs, but it returns a reasonable approximation of the division result if the arguments are floats or complex. This makes expressions expecting float or complex results `error-prone when integers are not expected but possible as inputs`. – Bekhruz Rakhmonov Oct 04 '22 at 17:55