Category: Python

Python: Make division always produce real numbers

April 15th, 2008 | No Comments | Print

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

Recommended Reading

Like this article?

Subscribe to the  RSS feed, or to  daily email updates, right now!

Share and enjoy:  Digg  del.icio.us  TwitThis  Facebook

Leave a Reply