473,289 Members | 1,953 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,289 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 1404
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...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

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.