By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,550 Members | 1,189 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,550 IT Pros & Developers. It's quick & easy.

printing anomaly

P: n/a
What's the deal with this?
print 3.2 3.2 print [3.2] [3.2000000000000002]


Yes, I know that 3.2 isn't an exact binary fraction. I'm wondering
why it's converted differently depending on whether it's in a list.
Jul 18 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
In article <7x************@ruckus.brouhaha.com>,
Paul Rubin <http://ph****@NOSPAM.invalid> wrote:
What's the deal with this?
>>> print 3.2 3.2 >>> print [3.2] [3.2000000000000002] >>>
Yes, I know that 3.2 isn't an exact binary fraction. I'm wondering
why it's converted differently depending on whether it's in a list.


That's intersting. It looks like it's the difference between str() and
repr():
print str(3.2) 3.2 print repr(3.2)

3.2000000000000002
Jul 18 '05 #2

P: n/a
Paul Rubin wrote:
What's the deal with this?
>>> print 3.2 3.2 >>> print [3.2] [3.2000000000000002] >>>


Yes, I know that 3.2 isn't an exact binary fraction. I'm wondering
why it's converted differently depending on whether it's in a list.


repr vs. str. The str of the sequence types prints the repr of their
contents.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
History is a set of lies agreed upon.
-- Napoleon Bonaparte
Jul 18 '05 #3

P: n/a
Paul Rubin wrote:
What's the deal with this?
>>> print 3.2 3.2 >>> print [3.2] [3.2000000000000002] >>>
Yes, I know that 3.2 isn't an exact binary fraction. I'm wondering
why it's converted differently depending on whether it's in a list.


It's not. The difference is that print uses str() to convert
its arguments to strings, whereas lists always use repr()
to convert their elements to strings, regardless of whether
you use str() or repr() on the list as a whole.

A simple experiment shows the difference between str()
and repr() on floats:

Python 2.3.4 (#1, Jun 30 2004, 16:47:37)
[GCC 3.2 20020903 (Red Hat Linux 8.0 3.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
str(3.2) '3.2' repr(3.2)

'3.2000000000000002'

--
Greg Ewing, Computer Science Dept,
University of Canterbury,
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg
Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.