473,375 Members | 1,542 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,375 software developers and data experts.

Floating point Arithmetic seems odd in Python

What do you think about this?
Expand|Select|Wrap|Line Numbers
  1. >>> trans = [{'debit':'50.6'},{'debit':'20.2'}]
  2. >>> for row in trans:
  3.     row['debit'] = float(row['debit'])
  4.  
  5. >>> trans
  6. [{'debit': 50.600000000000001}, {'debit': 20.199999999999999}]
  7.  
I Just want to convert some string to float but I get these weird numbers. Is it a bug in Python or am I doing something wrong?
Oct 27 '07 #1
7 1408
bvdet
2,851 Expert Mod 2GB
What do you think about this?
Expand|Select|Wrap|Line Numbers
  1. >>> trans = [{'debit':'50.6'},{'debit':'20.2'}]
  2. >>> for row in trans:
  3.     row['debit'] = float(row['debit'])
  4.  
  5. >>> trans
  6. [{'debit': 50.600000000000001}, {'debit': 20.199999999999999}]
  7.  
I Just want to convert some string to float but I get these weird numbers. Is it a bug in Python or am I doing something wrong?
You are doing nothing wrong, nor is there a bug in Python. Floating point numbers cannot always be represented with 100% accuracy. When testing for equality, it is necessary to compare the numbers to a very small one. Here is an example:
Expand|Select|Wrap|Line Numbers
  1. ....def equiv(self, other, epsilon = 0.000001):
  2.         '''
  3.         Compares two vectors, returns a tuple of 1, 0, or -1 values
  4.         Interactive example:
  5.         >>> Point(1,1,5).equiv(Point(2,0,5))
  6.         (-1, 1, 0)
  7.         >>> 
  8.         '''
  9.         def comp(x,y):
  10.             if abs(x-y) < epsilon: return 0
  11.             elif x > y: return 1
  12.             else: return -1
  13.         return tuple(map(comp, self, other))
Oct 27 '07 #2
bartonc
6,596 Expert 4TB
What do you think about this?
Expand|Select|Wrap|Line Numbers
  1. >>> trans = [{'debit':'50.6'},{'debit':'20.2'}]
  2. >>> for row in trans:
  3.     row['debit'] = float(row['debit'])
  4.  
  5. >>> trans
  6. [{'debit': 50.600000000000001}, {'debit': 20.199999999999999}]
  7.  
I Just want to convert some string to float but I get these weird numbers. Is it a bug in Python or am I doing something wrong?
If you take it down to the "ones-and-zeros" where floating point numbers (and every thing else) must eventually be represented, you'll find that there is no way to store 20.2 precisely. Given the number of bits available, that's a pretty good approximation, though. Going the other way (float to text) is handled correctly:
Expand|Select|Wrap|Line Numbers
  1. >>> a = 20.2
  2. >>> a
  3. 20.199999999999999
  4. >>> "%.2f" %a
  5. '20.20'
  6. >>> 
Oct 27 '07 #3
Thanks a lot bartonc and bvdet!

I was afraid I would have to rip up my whole code to work around this ;-). Interesting with that binary-thing. Never thought about that before.

Hahaha, just found the python-docs:
[HTML]Note that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a bug in your code either.
[/HTML]

Guess I should have looked there first, if I knew what I was looking for :-).
Oct 27 '07 #4
bartonc
6,596 Expert 4TB
Thanks a lot bartonc and bvdet!

I was afraid I would have to rip up my whole code to work around this ;-). Interesting with that binary-thing. Never thought about that before.

Hahaha, just found the python-docs:
[HTML]Note that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a bug in your code either.
[/HTML]

Guess I should have looked there first, if I knew what I was looking for :-).
Just thought that I'd add the link: B. Floating Point Arithmetic: Issues and Limitations

Thanks for supplying that quote from the docs.
Oct 27 '07 #5
elcron
43
A wrapper class could fix your representation problem. Though you would have to create instances of it rather than float.
Expand|Select|Wrap|Line Numbers
  1. class Decimal(float):
  2.     def __repr__(self):
  3.         return '%.2f' %(self)
  4.  
Oct 27 '07 #6
bartonc
6,596 Expert 4TB
A wrapper class could fix your representation problem. Though you would have to create instances of it rather than float.
Expand|Select|Wrap|Line Numbers
  1. class Decimal(float):
  2.     def __repr__(self):
  3.         return '%.2f' %(self)
  4.  
Nice thought, but there is a name clash there...
Expand|Select|Wrap|Line Numbers
  1. >>> from decimal import Decimal
Oct 27 '07 #7
bartonc
6,596 Expert 4TB
Nice thought, but there is a name clash there...
Expand|Select|Wrap|Line Numbers
  1. >>> from decimal import Decimal
And here's that link:5.6 decimal -- Decimal floating point arithmetic[HTML]New in version 2.4.

The decimal module provides support for decimal floating point arithmetic. It offers several advantages over the float() datatype:

* Decimal numbers can be represented exactly. In contrast, numbers like 1.1 do not have an exact representation in binary floating point. End users typically would not expect 1.1 to display as 1.1000000000000001 as it does with binary floating point.[/HTML]
Oct 27 '07 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Michael Hudson | last post by:
Does anyone (Tim?) have (ideally Python, but I can cope) code implementing the fixed-format algorithm from the Subject: named paper by Burger & Dybvig? Cheers, mwh -- <Erwin> #python FAQ:...
3
by: Mantorok Redgormor | last post by:
What have some of you guys read to have a solid understanding of how floating-point numbers are represented or handled by the processor and what the difference between single and double precision...
687
by: cody | last post by:
no this is no trollposting and please don't get it wrong but iam very curious why people still use C instead of other languages especially C++. i heard people say C++ is slower than C but i can't...
24
by: j0mbolar | last post by:
C supports single precision floating point and double precision floating point but does it support fixed floating point? i've read that fixed floating point is more accurate than single precision...
13
by: Bern McCarty | last post by:
I have run an experiment to try to learn some things about floating point performance in managed C++. I am using Visual Studio 2003. I was hoping to get a feel for whether or not it would make...
32
by: ma740988 | last post by:
template <class T> inline bool isEqual( const T& a, const T& b, const T epsilon = std::numeric_limits<T>::epsilon() ) { const T diff = a - b; return ( diff <= epsilon ) && ( diff >= -epsilon );...
6
by: yong321 | last post by:
With this script <script> alert(8/(3-8/3)) </script> I hope to get 24, but I get 23.99999999999999 in IE 6.0.2800 and Firefox 1.5.0.4. alert(6/(1-3/4)) returns 24 as expected. I see a...
31
by: Mark Dickinson | last post by:
On SuSE 10.2/Xeon there seems to be a rounding bug for floating-point addition: dickinsm@weyl:~python Python 2.5 (r25:51908, May 25 2007, 16:14:04) on linux2 Type "help", "copyright",...
2
by: Rob Clewley | last post by:
Dear Pythonistas, How many times have we seen posts recently along the lines of "why is it that 0.1 appears as 0.10000000000000001 in python?" that lead to posters being sent to the definition...
6
by: fred8865 | last post by:
Hi all, I understand that due to different arithmetic used in floating points they are just approximations. Hence, 180/100=1 in my python interpreter. How can I tackle this problem of inaccurate...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.