简体   繁体   中英

operator precedence of floor division and division

I have trouble understanding why python returns different results for these 2 statements:

-1 // 3/4 and -1 // 0.75

The first one returns -0.25 and the second on returns -2 .

The way i understand it, the / operator is executed before // , thus those 2 statements should have the same result.

edit: I was referring to a document provided by my university. I misinterpreted that. Official python documentation proves me wrong. Thanks for all the quick answers.

The / and // operators have the same precedence according to the documentation so they are evaluated from left to right when used in the same expression. -1 // 3/4 is therefore equivalent to (-1 // 3)/4 rather than -1 // (3/4) .

The way i understand it, the / operator is executed before // , thus those 2 statements should have the same result.

Your understanding is incorrect. / and // have the same precedence and have left associativity, meaning that Python performs the leftmost operation first - in your case, the / .

The Expressions documentation has a section about Operator Precedence . Operators in the same box have the same precedence.

Thus, the table tells you that // and / have equal precedence, so

-1 // 3/4 parses as

>>> (-1//3)/4
>>> -0.25

no, they have the same precedence, so they're evaluated from left to right.

-1//3 is rounded (to the least integer) integer division, so you get -1 divided by 4 : 0.25

When you have doubts, it doesn't cost much to throw in a couple of parentheses.

Think of these from an order of operations standpoint:

-1 // 3/4

This will perform -1 "floor" 3 , which yields -1 , which then divided by 4 yields -0.25 .

Whereas:

-1 // 0.75

This will simply "floor" the operation straight away and yield -2.0 .

According to documentation, Multiplication * , matrix multiplication @ , division / , floor division // , remainder % all have same precedence.

When two operators have the same precedence, associativity helps to determine the order of operations.

Now regarding your question; both / and // have same precedence, and if both of them are present in an expression, left one is evaluated first based on left-to-right associativity .

// is essentially an operator for flooring division.

So 1 // 0.75 is essentially flooring 1.333 which is 1

-1 // 0.75 is essentially flooring -1.333 which is -2.

Hope this makes sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM