954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Problem with Decimal Floating Point

We know that 0.1 + 0.1 + 0.1 - 0.3 = 0.0
But in python 0.1 + 0.1 + 0.1 - 0.3 = 5.5511151231257827e-017

Is there any way I can get 0.0...??

knan
Light Poster
29 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

Well a simple fix would be to multiply everything by 10. Ie:

import os
print float(1+1+1-3)/10
os.system("pause")
SgtMe
Nearly a Posting Virtuoso
1,205 posts since Oct 2009
Reputation Points: 68
Solved Threads: 85
 

To be at sure side add in beginning of your numeric Python 2 code:

from __future__ import division


This makes 1/4 produce 0.25, not 0 (integer division). For integer division use // operator.

pyTony
pyMod
Moderator
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
 

Start with this documentation page http://docs.python.org/tutorial/floatingpoint.html .

A problem is that python's 0.1 is not the mathematical 0.1 because 0.1 can not be represented exactly as a machine binary number.

Gribouillis
Posting Maven
Moderator
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
 

The limits of floating point numbers
http://www.lahey.com/float.htm
http://docs.python.org/tutorial/floatingpoint.html
Use decimal for more precision.

from decimal import Decimal as dec

# 0.1 + 0.1 + 0.1 - 0.3 = 0.0
x = dec("0.1")
y = dec("0.3")
print x + x + x - y
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

Thank you very much everyone... Now i understand the reason behind it... Thank you!

knan
Light Poster
29 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: