5

In terms of the resulting value (ignoring the resulting data type), are the following the same in Python if x and y are both numbers?

int(x / y)
x // y

If so, which is better to use in real application? And why?

P.S. Are there any other methods in Python that achieve similar result but more suitable in different use cases? For example, if y is 2^n, then we can do bitwise shifting - that's all I know.

5
  • "In Python, we can perform floor division (also sometimes known as integer division) using the // operator. This operator will divide the first argument by the second and round the result down to the nearest whole number, making it equivalent to the math." Commented Apr 2, 2024 at 11:37
  • 1
    x/y will have limited precision so they are not equivalent. Commented Apr 2, 2024 at 11:37
  • 2
    Try x = -3 and y = 2. Commented Apr 2, 2024 at 11:37
  • math.floor(3/2) is an alternative for 3//2. It always gives an Integer as result. Commented Apr 2, 2024 at 11:52
  • 1
    @MrIrrelevant They don't always give the same value. Try with x=10**30 and y=3. Commented Apr 2, 2024 at 12:01

1 Answer 1

9

They have different behaviours.

a//b rounds down, so 5//-2 == -3.

int(a/b) rounds towards zero, so int(5/-2) == -2

Edit to add: I just realized something important! a/b always produces a float. If a is too large for the quotient to be represented by a float (i.e, the result is greater than about 10^308), then a/b will fail with an OverflowError. This does not happen with a//b. Observe:

>>> int(10**1000/3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: integer division result too large for a float
>>> 10**1000//3
333333333333333333333333333333333333333333333333333...

Additionally, the floating point number resulting from the division will have rounding errors. Beyond about 2^53, 64-bit floating point numbers cannot accurately represent all integers, so you will get incorrect results:

>>> int(10**22/3)
3333333333333333508096
>>> 10**22//3
3333333333333333333333
Sign up to request clarification or add additional context in comments.

2 Comments

A float isn't just limited by size, it's also limited by resolution. Look at int(10**100/3).
Right, good point @MarkRansom. I'll add that to the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.