selinap.com

To leave furtively and stealthily.


Home » Python

Python: Make division always produce real numbers

April 15th, 2008

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:

1
2
3
4
5
6
7
8
>>> 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.

1
2
3
4
>>> from __future__ import division   
 
>>> print 7/3  
2.5

Related Articles:

Popular Articles:

Spread/Promote this article.

Digg | Del.icio.us | Stumble | Y! MyWeb | Y! Buzz | Fave It! | Reddit

Subscribe for free.

 Subscribe to Selinap.com feed right now!

 Get Updates by Email

Tags: , , ,

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">



© Copyright 2008 - 2009 selinap.com
Entries (RSS) and Comments (RSS).