!!! 2.1, 2.2, 2.2.1, PYTHON BUGS ????

David Bolen db3l at fitlinxx.com
Thu May 30 22:32:40 EDT 2002


"David K. Trudgett" <dkt at registriesltd.com.au> writes:

> > point was changed between Python 1.5.2 and Python 2.1.  If you are
> > bothered by the representational rounding for 0.1, you can always
> > truncate the answer to fewer decimal places.  
> 
> Yes, which is what one would normally do, probably, depending on how
> quick and dirty the program is.

By the way, while the interactive interpreter is one very visible
place where you get hit by the change, it's not very hard to avoid for
simple expressions if you prefer the older (rounded, imprecision
hidden) approach for output.

By default an expression is shown in the interpreter using repr(),
which is what changed to help ensure it maintains as many significant
digits as likely to be usable under IEEE rules (e.g., for converting
back and forth to strings as precisely as possible).  But str()
conversions still use the more readable rules.

E.g.:

Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> str(0.1)
'0.1'
>>> repr(0.1)
'0.1'
>>> 0.1
0.1
>>> print 0.1
0.1
>>> ^Z

Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> str(0.1)
'0.1'
>>> repr(0.1)
'0.10000000000000001'
>>> 0.1
0.10000000000000001
>>> print 0.1
0.1

So if you just "print" your expressions at the interactive prompt
you'll get the same thing under all Python releases, since print
internally converts non-string arguments to string with str().  The
same would be true for any use of str() explicitly in code or '%s' as
a formatting operation.

If you really want the older behavior, in the later versions you can
also override sys.displayhook with your own function for default
display of interactive results.  Here's a simple one that makes the
default use print:

    import sys, __builtin__

    def default_display_hook(x):
	if x is None:
	    return
	print repr(x)
	__builtin__._ = x

    sys.displayhook = default_display_hook

What's difficult to avoid is recursive structures (lists,
dictionaries, etc...) since repr() is also automatically used for the
inner objects, and that's much harder to override.  But in any code
that you may be manipulating such objects for end user display you
should be able to format the objects yourself (with str() or '%s') to
get the "nicer" output.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list