Star Rider
Star Rider

Reputation: 107

Python 2.7.10 inbuilt calculation trouble

Can you explain what's happening with python shell..

>>> 6/7   
0

>>> -6/7   
-1

>>> -(6/7)    
0

Upvotes: 0

Views: 43

Answers (2)

polarise
polarise

Reputation: 2413

If you want to perform floating point division you should set the following import at the top of your script or as the first line in your Python shell:

from __future__ import division

This will ensure that you get proper results. If you want to perform integer division use // instead.

Upvotes: 1

AdmPicard
AdmPicard

Reputation: 439

With the / operator python always rounds to minus infinity (so to the "more negative" value) if you input integers, like stated in the python docs. This explains the described behavior.

So 6/7 would be 0.857... and gets rounded to 0 while -6/7 gives -0.857... and will be rounded to -1. Finally -0 equals 0.

Upvotes: 1

Related Questions