Back to Community
Annoying behavior

In Research on a windows 10 machine using chrome :

7/8 returns 0 " incorrectly '
7./8 returns .87 "correctly"

apparently a rounding option or float option needs to be adjusted.

Any way around this.

4 responses

from __future__ import division

Loading notebook preview...
Notebook previews are currently unavailable.

Thank you. Works fine .


Here is a post to elaborate on Alex's response.

Basically, iPython assumes if there are two integers then you want an integer output. If one or both are real then you want a real output. In Python 3 this behavior has been changed to always return a real. To get an integer result the 'floor' operator // must be used. By using the statement "from future import division" one is over-riding the base iPython division with that used in the Python 3 (which returns a real in all cases).


This "annoying behavior", integer division, is a feature of Python, and as old as Fortran.

Workarounds (other than using Python's "future division"):
- when you're dividing two number literals, make sure one of them is a floating-point number, eg. write 7./8 as you did, or 7/8., or 7./8.
- add 0.0 to one, to force implicit conversion to floating point: (x+0.0)/y
- explicitly force one to floating point: float(x)/y
- explicitly force both to floating point: float(x)/float(y)

The last option allows x and y to be of any type convertible to float, eg. str.