Python integer split operator

Asked

Viewed 1,867 times

6

Can anyone explain why this function returns -2 and not -1?

print(-3//2)

The operator // does not return the entire part of the division?

  • 1

    Welcome George, this link will help you: https://pythonhelp.wordpress.com/2013/06/30/behaviorunexpectedlyin the entire division/

  • 1

    It is worth noting that the link that Luiz Augusto sent is in python2, so read 3 // 2 when you see 3 / 2 in the article. I did not find an official documentation that explains, but there is a article by Digital Ocean which explains.

  • Okay, I found something on official documentation on the integer division difference between Python versions 2 and 3.

1 answer

11


If you check the documentation of numerical types will see that the operator // contains the following description and observation:

x // y: floored quotient of x and y

*...The result is Always rounded Towards Minus Infinity...

Free translation:

x // y: x and y quotient floor

*...The result is always rounded to negative infinity...

As the result of your operation would be -3/2 == -1.5, if you apply to floor function (math.floor in python), or wind it up towards the negative infinity, you will have as a result -2.

You can also check the entrance "Why does -22 // 10 Return -3?" from the Python FAQ to better understand what motivated this decision.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.