Python: Make division always produce real numbers

A division of 7/3 in Python will gives a result of 2. However, this is not correct. Since Python always assume that the numbers are whole numbers, the result will be truncated from 2.5 to 2.

A work around is to write one or both of the numbers as a decimal:

>>> print 7/3.0
2.5  

>>> print 7.0/3
2.5  

>>> print 7.0/3.0
2.5

In order to change this behaviour of Python, throughout the program execution, so that Python will always produce real numbers, a module division has to be imported.

>>> from __future__ import division   

>>> print 7/3
2.5
If you are new here, you might want to subscribe to the RSS feed or newsletter.

Enter your email address:

Related

This entry was posted in Python and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>