0

Here is a sample

a = 5 //2 
b = int(5/2)

We all know that a = b = 2. My question is

can a // b  allways equal int(a/b) ?

I can't find a wrong example...so far

McCree Feng
  • 179
  • 4
  • 12
  • Relevant links for self-learning: [`int()`](https://docs.python.org/3/library/functions.html#int), and [`//` (floor division)](https://docs.python.org/3/reference/expressions.html#binary-arithmetic-operations) (name already gives a hint) – Tomerikoo Sep 16 '20 at 13:43
  • `a//b` gives a quotient: the number you would get if you long-divided those numbers and threw away the remainder. `int(a/b)` just rounds a completely divided `a/b` number off toward zero. Like the answer below said, negative numbers are the curious case. – Aravind Suresh Thakidayil Sep 16 '20 at 13:44

3 Answers3

0

Yes: // always rounds down, whereas int(...) rounds towards zero, so they can have different results for negative numbers.

>>> -1 // 2
-1
>>> int(-1 / 2)
0
kaya3
  • 47,440
  • 4
  • 68
  • 97
  • Just for negative numbers? I'm getting different results for `1 // 0.1` and `int(1/0.1)` as well. – Wander Nauta Sep 16 '20 at 13:43
  • 1
    @WanderNauta Well, you can also get different results by writing a class with different implementations of `__truediv__` and `__floordiv__`; I think the question is implicitly about integers, but I didn't say it is only for negative numbers. The question just asked for an example. – kaya3 Sep 16 '20 at 13:45
0

You can see the difference when you start trying it with negative numbers

>>> -3.5//2
-2.0
>>> int(-3.5/2)
-1
>>>
0

In addition to above, take the following case :

a = 53.76
b = 7.37

The output of a // b operation is a real number (7.0) while the output of int(a/b) will always be an integer (7).

Small difference ...

aasoo
  • 100
  • 1
  • 8
Sachin
  • 85
  • 9