operator precedence of floor division and division

笑着哭i 提交于 2020-01-11 08:48:09

问题


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.


回答1:


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).




回答2:


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 /.




回答3:


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



回答4:


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.




回答5:


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.




回答6:


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.




回答7:


// 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.



来源:https://stackoverflow.com/questions/53072731/operator-precedence-of-floor-division-and-division

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!