This math scares me

David Bolen db3l at fitlinxx.com
Wed Mar 14 02:47:16 CET 2001


costas at meezon.com (Costas Menico) writes:

> Fortunately I discovered I can use "print 5.01 + 5.54" and it does the
> job. It has the extra intelligence built into it to autoformat

In case you're interested in why it has this difference, Python
generally has two ways of getting printable representations of
objects, which you can also access with the built-in functions str()
and repr().

str() is intended to provide a string of a "nice" or printable form of
the object, and generally avoids extra quoting, and in the case of
floating point numbers will perform some implicit rounding (or
truncation - well, one of the two).

repr() is intended to provide a string representation of the object
itself, such that as much as possible, you could pass the string to
eval() to recreate an instance of the object.

When you evaluate an expression at the interactive prompt (in recent
Python releases), Python will display the result object from the
expression using repr().  However, the print statement uses the str()
method on its arguments.

You can also obtain the same output as str() by using the "%s"
operator within a format string or by calling it directly.  

Note that as pointed out by many others, the repr() output is actually
more precise for what floating point values you are really storing in
the computer.  While print may make the output look nicer, you need to
be aware that the values are not truly as exact as they appear when
formatted with str(), which can be critical if you intend to use the
floating point values for any serious computations.

--
-- 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