Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 875
Conwear Avatar asked Oct 30 '18 20:10

Conwear


People also ask

Which operator is used for floor division?

The real floor division operator is “//”. It returns the floor value for both integer and floating-point arguments.

What is difference between division and floor division?

Floor division is a normal division operation except that it returns the largest possible integer. This integer is either less than or equal to the normal division result. Floor function is mathematically denoted by this ⌊ ⌋ symbol.

What is the difference between division operator and floor division operator with an example?

Right Answer is: The division operator is performed on two operands. This means that we get an exact division result. For example: print(9/4.0) produces 2.25. The floor division performs an integer division.

What is the correct order of operator precedence?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .


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

like image 58
blhsing Avatar answered Nov 15 '22 07:11

blhsing