Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why -1//2 = -1 but int(-1/2) = 0?

I found that -1 // 2 is equal to -1 (Why not 0?), but int(-1 / 2) is equal to 0 (as I expected).
It’s not the case with 1 instead of -1, so both 1 // 2 and int(1 / 2) is equal to 0.

Why the results are different for -1?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In Python, the division operator / and the floor division operator // have different behavior.

The division operator / returns a floating-point number that represents the exact quotient of the division. In the case of -1/2, the quotient is -0.5. When you cast it to int, it rounds the number up to 0.

The floor division operator // returns the quotient of the division rounded down to the nearest integer. In the case of -1//2, the quotient is -1, because -1 divided by 2 is -0.5, which is rounded down to -1.

That’s why -1//2 = -1 and int(-1/2) = 0 in python.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading