f



Float to String "%.7e" - diff between Python-2.6 and Python-2.7

When formatting a float using the exponential format, the rounding is different in Python-2.6 and Python-2.7. See example below.
Is this intentional?

Is there any way of forcing the Python-2.6 behavior (for compatibility reasons when testing)?

>c:\python26\python
r:\asiData\abaObjects\lib>c:\python26\python
Python 2.6.5 (r265:79096, Mar 19 2010, 18:02:59) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = [2.096732130e+02,2.096732140e+02,2.096732150e+02,2.096732151e+02,2.096732160+02]
>>> for a in x:
....     print ' %.9e    %.7e'%(a,a)
....
 2.096732130e+02    2.0967321e+02
 2.096732140e+02    2.0967321e+02
 2.096732150e+02    2.0967322e+02 <<<<<<<<
 2.096732151e+02    2.0967322e+02
 4.096732160e+00    4.0967322e+00
>>> for a in x:
....     print '%.9e   %.7e'%(-a,-a)
....
-2.096732130e+02   -2.0967321e+02
-2.096732140e+02   -2.0967321e+02
-2.096732150e+02   -2.0967322e+02 <<<<<<<<
-2.096732151e+02   -2.0967322e+02
-4.096732160e+00   -4.0967322e+00
>>> ^Z

>c:\python27\python
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = [2.096732130e+02,2.096732140e+02,2.096732150e+02,2.096732151e+02,2.096732160+02]
>>> for a in x:
....     print ' %.9e    %.7e'%(a,a)
....
 2.096732130e+02    2.0967321e+02
 2.096732140e+02    2.0967321e+02
 2.096732150e+02    2.0967321e+02 <<<<<<<<
 2.096732151e+02    2.0967322e+02
 4.096732160e+00    4.0967322e+00
>>> for a in x:
....     print '%.9e   %.7e'%(-a,-a)
....
-2.096732130e+02   -2.0967321e+02
-2.096732140e+02   -2.0967321e+02
-2.096732150e+02   -2.0967321e+02 <<<<<<<<
-2.096732151e+02   -2.0967322e+02
-4.096732160e+00   -4.0967322e+00
>>> ^Z

>
Andrew MacKeith
0
andrew
10/30/2012 2:47:51 PM
comp.lang.python 77058 articles. 6 followers. Post Follow

3 Replies
648 Views

Similar Articles

[PageSpeed] 26

andrew.mackeith@3ds.com wrote:

> When formatting a float using the exponential format, the rounding is
> different in Python-2.6 and Python-2.7. See example below. Is this
> intentional? 
> 
> Is there any way of forcing the Python-2.6 behavior (for compatibility
> reasons when testing)? 
> 
It isn't Python 2.6 behaviour, it looks more like a bug in your particular 
version of 2.6. This one matches what you are seeing on 2.7:

[dbooth@localhost ~]$ /opt/local/bin/python2.6
Python 2.6.7 (r267:88850, Jan  5 2012, 16:18:48)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = [2.096732130e+02,2.096732140e+02,2.096732150e+02,2.096732151e+
02,2.096732160+02]
>>> for a in x:
....   print ' %.9e    %.7e'%(a,a)
....
 2.096732130e+02    2.0967321e+02
 2.096732140e+02    2.0967321e+02
 2.096732150e+02    2.0967321e+02
 2.096732151e+02    2.0967322e+02
 4.096732160e+00    4.0967322e+00

Note that the rounding shown here is correct; the actual value is slightly 
less than 5 in the last place:

[dbooth@localhost ~]$ /opt/local/bin/python2.6 -c "print('%.20e'%
2.096732150e+02,'%.7e'%2.096732150e+02)"
('2.09673214999999999009e+02', '2.0967321e+02')

What do you get printing the value on 2.6 with a '%.20e' format? I seem to 
remember that 2.7 rewrote float parsing because previously it was buggy.

-- 
Duncan Booth http://kupuguy.blogspot.com
0
duncan.booth (1734)
10/30/2012 3:10:54 PM
On 10/30/2012 10:47 AM, andrew.mackeith@3ds.com wrote:
> When formatting a float using the exponential format, the rounding is different in Python-2.6 and Python-2.7. See example below.
> Is this intentional?
>
> Is there any way of forcing the Python-2.6 behavior (for compatibility reasons when testing)?
>
>> c:\python26\python
> r:\asiData\abaObjects\lib>c:\python26\python
> Python 2.6.5 (r265:79096, Mar 19 2010, 18:02:59) [MSC v.1500 64 bit (AMD64)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> x = [2.096732130e+02,2.096732140e+02,2.096732150e+02,2.096732151e+02,2.096732160+02]
>>>> for a in x:
> ...     print ' %.9e    %.7e'%(a,a)
> ...
>  2.096732130e+02    2.0967321e+02
>  2.096732140e+02    2.0967321e+02
>  2.096732150e+02    2.0967322e+02 <<<<<<<<
>  2.096732151e+02    2.0967322e+02
>  4.096732160e+00    4.0967322e+00
>

Looks to me that the indicated value was rounded wrong in 2.6, so
apparently that was fixed in 2.7

The actual binary fp value stored for 2.096732150 e+02 is slightly
smaller than the decimal string specified, so it'll round towards
1.0967321 when you specify 7 digits.

I don't know of any way to re-introduce the earlier version.  But you
could fix them both by using Decimal, where there's no quantization
error.  Or if this is a fake example, adapt by just validating that the
results are 'close'

-- 

DaveA

0
d9555 (591)
10/30/2012 3:13:53 PM
 <andrew.mackeith <at> 3ds.com> writes:

> When formatting a float using the exponential format, the rounding is
> different in Python-2.6 and Python-2.7. See example below.  Is this
> intentional?

Yes, in a sense.  Python <= 2.6 uses the OS-provided functionality (e.g., the C
library's strtod, dtoa and sprintf functions) to do float-to-string and
string-to-float conversions, and hence behaves differently from platform to
platform.  In particular, it's common for near halfway cases (like the one
you're looking at here) and tiny numbers to give different results on different
platforms.  Python >= 2.7 has its own built-in code for performing
float-to-string and string-to-float conversions, so those conversions are
platform- independent and always correctly rounded.  (Nitpick: it's still
theoretically possible for Python 2.7 to use the OS code if it can't determine
the floating-point format, or if it can't find a way to ensure the proper FPU
settings, but I don't know of any current platforms where that's the case.)

> Is there any way of forcing the Python-2.6 behavior (for compatibility
> reasons when testing)?

Not easily, no.

--
Mark


0
10/31/2012 3:39:53 PM
Reply:

Similar Artilces:

Python 2.6.6 on Windows 7 problem
Hello! If I start python -v, I get "# installing zipimport hook import zipimport # builtin # installed zipimport hook 'import site' failed; traceback ImportError: No module named site" Entering any command yields "LookupError: no codec search functions registered: can't find encoding" I reinstalled it, but this makes no difference. Any suggestions? Thanks Mark ...

..\..\Python-2.5.2\Include\pyport.h(117) : fatal error C1189: #error : "Python needs a typedef for Py_ssize_t in pyport.h."
When I try and compile using VS2003 for Release. Compiles fine for Debug. In a hurry (should be gardening). Any solution? TIA Bill ...

python said : "1, 2, 3, 6, 7, manbo !"
At the python2.3.2 prompt >>> a = range(8) >>> for b in a: if b == 4: a.remove(b) else: print b 0 1 2 3 6 7 Why 5 does not appear ? (this was the source of a deep bug in a 4000+ lines networked program...) RodrigoB (corrected the identation) > At the python2.3.2 prompt > > >>> a = range(8) > >>> for b in a: > ...........if b == 4: > ................a.remove(b) > ...........else: > ................print b > > > 0 > 1 > 2 > 3 > 6 > 7 > > > Why 5 does not appear ? (this was the source of ...

Python 2.0 / Python 2.2
Hallo newsgroup, I have some questions concerning Python 2.2. First question: I try to port source code from Python 2.0 to Python 2.2.The following source code works with Python 2.0. If I compile it with Python 2.2, the modul "tci" is not imported. "tci" is a python module written by us. How can I change the source code to get it working with Python 2.2.? Py_Initialize(); PyStr = Py_BuildValue("s", TCIHome); PyModule = PyImport_ImportModule("sys"); PyList = PyObject_GetAttrString(PyModule, "path"); PyList_Insert(PyList, 0, PyStr); if (PyEr...

python-2.6.2 Exception: TypeError: "'NoneType' object is not callable" in ignored
The following code produces an error (python-2.6.2). Either of the following eliminates the error: . assign something besides mod1 (the newly-created module) to d1 . remove the call to shelve.open Why is there an error produced in the first place? What is the interaction between d1, mod1, and shelve about? This code runs without error in python-3.1 $ cat test1.py import test2 newmodule = test2.load() $ cat test2.py import imp import shelve def load(): text='import test2\n' text += '''print('...

Moving from Python 2 to Python 3: A 4 page "cheat sheet"
I've produced a 4 page document that provides a very concise summary of Python 2<->3 differences plus the most commonly used new Python 3 features. It is aimed at existing Python 2 programmers who want to start writing Python 3 programs and want to use Python 3 idioms rather than those from Python 2 where the idioms differ. It uses Python 3.1 syntax since that looks like being the standard for a few years in view of the language moratorium. The document is U.S. Letter size but will also print fine on A4 printers. It is available as a free PDF download (no registration ...

Moving from Python 2 to Python 3: A 4 page "cheat sheet"
I've produced a 4 page document that provides a very concise summary of Python 2<->3 differences plus the most commonly used new Python 3 features. It is aimed at existing Python 2 programmers who want to start writing Python 3 programs and want to use Python 3 idioms rather than those from Python 2 where the idioms differ. It uses Python 3.1 syntax since that looks like being the standard for a few years in view of the language moratorium. The document is U.S. Letter size but will also print fine on A4 printers. It is available as a free PDF download (no registration ...

Python 2.7.9, 3.4.2 won't verify SSL cert for "verisign.com"
Python 2.7.9, Windows 7 x64. (also 3.4.2 on Win7, and 3.4.0 on Ubuntu 14.04) There's something about the SSL cert for "https://www.verisign.com" that won't verify properly from Python. The current code looks like this: def testurlopen(host, certfile) : port = httplib.HTTPS_PORT sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) context = ssl.create_default_context(cafile=certfile) sock = context.wrap_socket(sk, server_hostname=host) try: sock.connect((host,port)) except EnvironmentError as message : print(&quo...

urllib2 does not implement "with" Python 2.6
Somewhat to my surprise, in Python 2.6, with urllib2.urlopen(url) as fh : doesn't work. It fails with "AttributeError: addinfourl instance has no attribute '__exit__'". I thought that all the file-like objects supported "with" in 2.6. No? John Nagle John Nagle <nagle@animats.com> writes: > "AttributeError: addinfourl instance has no attribute '__exit__'". > > I thought that all the file-like objects supported "with" in 2.6. > No? I guess not. Use contextlib.closing. On 8/12/2010 1:3...

python 2.5.2 or Python 2.6 compilation problem on AIX 5.3
Hello: I am trying to compile Python 2.5.2 on AIX 5.3 with gcc 4.2.3. I am getting following error. (I also tried Python 2.6 with same error) creating build/temp.aix-5.3-2.5/share/tmhsdsd2/tmp/Python-2.5.2/ Modules gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall - Wstrict-prototypes -I. -I/share/tmhsdsd2/tmp/Python-2.5.2/./Include - I. -IInclude -I./Include -I/usr/local/include -I/share/tmhsdsd2/tmp/ Python-2.5.2/Include -I/share/tmhsdsd2/tmp/Python-2.5.2 -c /share/ tmhsdsd2/tmp/Python-2.5.2/Modules/_struct.c -o build/temp.aix-5.3-2.5/ share/tmhsdsd2/tmp/Python-2.5.2/Modules/_...

I don't undestand why sometime python (or other) add "tmpWvk7zy" (tmp + random string) after "buildout-eggs" in path of python script
Hi, first, I think that my question is generalist and don't impact only zopeproject and/or Paste package. Instance, when I trace (debug) some scripts, its name is "/home/harobed/ buildout-eggs/tmpWvk7zy/PasteScript-1.3.6-py2.5.egg/paste/script/ serve.py" instead of "/home/harobed/buildout-eggs/PasteScript-1.3.6- py2.5.egg/paste/script/serve.py". I don't understand why and who append "tmpWvk7zy" after "buildout-eggs". I don't know if it's related with python thread support. This trouble is very not useful to debug because pdb can'...

Pickle compatibility between Python 2.7 and python 3.2
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I have 10MB pickled structure generated in Python 2.7. I only use basic types (no clases) like sets, dictionaries, lists, strings, etc. The pickle stores a lot of strings. Some of them should be "bytes", while other should be "unicode". My idea is to import ALL the strings as bytes in Python 3.2 and navigate the data structure to convert the appropiate values to unicode, in a one-time operation (I version the structure, so I can know if this conversion is already done, simply storing a new version value). But I g...

"Deprecated sets module" with Python 2.6
I would appreciate help on correcting a problem when trying to create an *.exe file using py2exe via GUI2exe with Python 2.6.2. When using GUI2exe to create an *.exe I always get the following warning during the compile process: C:\Python26\lib\site-packages\py2exe\build_exe.py:16: DeprecationWarning: the sets module is deprecated import sets and this results in the creation of an *.exe file that can not be executed. On the other hand, if I use the same procedure (on the same Python code) with Python 2.5, there are no warnings and the *.exe works fine. The procedure used is that giv...

Some "pythonic" suggestions for Python
I love Python, and it is one of my 2 favorite languages. I would suggest that Python steal some aspects of the S language. ------------------------------------------------------- 1. Currently in Python def foo(x,y): ... assigns the name foo to a function object. Is this pythonic? Why not use the = operator like most other assignments? Define function objects as "function"s, let users put them where they want to. Get rid of lambda, get rid of def, only use = for assignments. foo = function(x,y) x+y*2 # Example S language code bar = foo bar(3,4) m = lapply( s, foo ) bb = lappl...

"which python" as a python command?
Hello, I'm trying to find out in a script where the location of the current python is. (I'm writing an installer script in python for a simple server application, so i'm going to do a find-replace in a bunch of files to give them the absolute path of the python binary. One thought might be to use the subprocess module, run "which python" as a subprocess, and then peek at stdout, but that seems way too complicated. Is there a simple solution for this in just a few lines of code? Cheers, Evan chardish@gmail.com wrote: > Hello, > > I'm trying to find out in...

RE: MySQLDB
Typo in my snippets: > cursor.execute("select * from T where C1 not in (%s)", params) should read cursor.execute("select * from T where C1 not in %s", params) since the converter-functions adds the parens already: > # this is used to translate lists/tuples to (1,2,3) format > # doesn't check to see if contents are actually numeric... > def _converter_set_ids(x, d): > if not len(x): return "(NULL)" > return "(%s)" % ", ".join([str(xx) for xx in x]) Cheerio, Marc. Don't you just want: cursor.execute(&quo...

python-2.7.3 vs python-3.2.3
Greetings; I have need of using a script written for python3, but the default python on wheezy is 2.7.3. I see in the wheezy repos that 3.2.3-6 is available. Can/will they co-exist peacefully? Thank you. Cheers, Gene Heskett -- "There are four boxes to be used in defense of liberty: soap, ballot, jury, and ammo. Please use in that order." -Ed Howdershelt (Author) Genes Web page <http://geneslinuxbox.net:6309/gene> On 26/01/16 13:26, Gene Heskett wrote: > Greetings; > > I have need of using a script written for python3, but the default pytho...

"#!/usr/bin/env python" vs. "#!/usr/bin/python"?
Hello I've seen both shebang lines to run a Python script on a *nix host: #!/usr/bin/env python #!/usr/bin/python What's the difference? Thank you. Gilles writes: > #!/usr/bin/env python > #!/usr/bin/python > > What's the difference? Not much if your python is /usr/bin/python: env looks for python and finds the same executable. When python is not /usr/bin/python but something else that is still found by your system, /usr/bin/env still finds it. For example, in a server where I work, python3 is installed as something like /opt/python/3.2...

Python 2.2.1 DLL extension causes "abnormal program termination"
Hello, Apologies if this has already been answered in here and I can't find it, but can anyone help with this problem? I hope the example code and comments state clearly enough what is happening, but if not, please ask me for further information. Thank in advance for any help. :-) Hugh #!/usr/bin/python # 1. DLL C++ source code # # #include <Python.h> # static PyObject* dummy(PyObject* self, PyObject* args) # { # return Py_None; # } # static PyMethodDef py_dll_test_methods[] = # { # { "dummy", dummy, METH_VARARGS, "dummy" }, # { 0,0,0,0 } ...

Compiling Python 2.6.4 on IRIX 6.5
I'm trying to compile Python 2.6.4 on my IRIX 6.5 machine. I have no idea how to fix this problem, and am hoping someone may know what to do. The closest thread I've found to this is http://bugs.python.org/issue4279, but that patch has already been added, yet I still get the error. The post makes reference to trying gmake, but I don't have that installed on this machine. I'm stuck with regular make. configure line: .../../configure --prefix=/usr/local/openSource/architectureIndependent --exec-prefix=/usr/local/openSource/IRIX6 --enable-shared --with- threads --wi...

How to crash Python in 1 easy step (python 2.2.2)
I'm not sure if this is a python bug or a bug in an associated library, and I'm not even sure how to correctly report it, but here is Anytime python is accepting keyboard input, whether it's with raw_input, or sitting on the command line waiting for the user to type code, you can crash python by holding ctrl+shift and then pressing enter. This is on a RedHat 9.0 system running on an Athlon 600. Basically everything about the system is standard except for what's been updated by RedHat itself. If anyone who has the time and ability to track down this bug needs more information, please email me. Paul Miller wrote: > I'm not sure if this is a python bug or a bug in an associated > library, and I'm not even sure how to correctly report it, but here is > Anytime python is accepting keyboard input, whether it's with > raw_input, or sitting on the command line waiting for the user to type > code, you can crash python by holding ctrl+shift and then pressing > enter. > > This is on a RedHat 9.0 system running on an Athlon 600. Basically > everything about the system is standard except for what's been updated > by RedHat itself. If anyone who has the time and ability to track > down this bug needs more information, please email me. I doubt it is a problem in Python, it works nicely on both my windows and my linux machines (python 2.2.3). Just a gut feeling: reinstall/upgrade your readline library..... --Irme...

urlopen differences between python 2.3.3 and python 2.2???
I am using the code below and it works correctly on python2.2 but gives me a 404 not found error when running on python2.3.3. Is there some difference? Maybe python 2.3.3 is sending different headers? The params string looks to be encoded identically, so must be something with urlopen. Does anyone have any suggestions to get this working from python2.3.3?? Thanks in advance! import httplib,urllib def signup(self, REQUEST): """ Allows us to automatically sign-up a user. """ email = REQUEST['Email'] first_name = REQUEST['First...

Both Python 2.5.2 and 2.7.2 flop the same way under Win 7
Months ago 2.5.2 stopped functioning on my Win7 PC, so a few days ago I uninstalled and installed. Same problem. If one right-clicks on a py file, IDLE is not shown in the menu as Edit with IDLE. After playing with matters I gave up, and uninstalled 2.5.2 and turned to 2.7.2. Same results. If I look at a 2.4 install on my laptop, I get the desired reference to Edit with IDLE. My guess is that Win 7 is behind this. If so, it's good-bye Python. Comments? On 17 Nov, 18:55, "W. eWatson" <wolftra...@invalid.com> wrote: > Months ago 2.5.2 stopped functioning on my Win...

[Python 2.7.3] What's the difference between these two uses of "for"?
N00b question. But here is the code: http://bin.cakephp.org/view/709201806 In the first example, the first for-loop is run and then the list is assigned to the tricky variable. But, what happens in the second example? Does the loop after "in" get run only once or multiple number of times? On 03/17/2013 05:58 PM, Yves S. Garret wrote: > N00b question. But here is the code: > > http://bin.cakephp.org/view/709201806 > > In the first example, the first for-loop is run and then the list is assigned to the tricky variable. But, what > happens in the second example? Does the loop after "in" get run only once or multiple number of times? Just once. The sorted fn is called just once, and the resulting list is iterated through. In your first case, the list is bound to (assigned to) a name so it is accessible afterwards. In the second case, it is available for garbage collection immediately after the loop finishes. Gary Herron On 2013.03.17 19:58, Yves S. Garret wrote: > N00b question. But here is the code: > > http://bin.cakephp.org/view/709201806 > > In the first example, the first for-loop is run and then the list is assigned to the tricky variable. But, what > happens in the second example? Does the loop after "in" get run only once or multiple number of times? > In the first example, sorted() returns a list, which is assigned to the name tricky (Python doesn...

python 2.3.4 for windows: float("NaN") throws exception
Hi my python 2.3.4 for windows refuse to execute line float("NaN"). It says: >>> float("NaN") Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: invalid literal for float(): NaN The same line works as expected on Linux and Solaris with python 2.3.4. Could anybody explain what is possibly wrong here? is it bug or feature? Andrei [asmirnov1234567890@yahoo.com] > my python 2.3.4 for windows refuse to execute line float("NaN"). It > says: > > >>> float("NaN") > Traceback (most re...

Web resources about - Float to String "%.7e" - diff between Python-2.6 and Python-2.7 - comp.lang.python

Resources last updated: 3/10/2016 8:29:41 PM