Back to Community
Annoying behavior

In Research on a windows 10 machine using chrome :

7/8 returns 0 " incorrectly '
but
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 .

Alfred,

Here is a post to elaborate on Alex's response. http://stackoverflow.com/questions/1267869/how-can-i-force-division-to-be-floating-point-in-python.

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

Dan

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.