How to print a number as if in the python interpreter?

Chris Rebert clp2 at rebertia.com
Sat Jul 7 00:59:28 CEST 2012


On Fri, Jul 6, 2012 at 3:38 PM, Peng Yu <pengyu.ut at gmail.com> wrote:
> Hi,
>
> In [2]: sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
> Out[2]: 0.9999999999999999
>
> In ipython, I got the above output. But I got a different output from
> "print". Is there a way to print exact what I saw in ipython?
>
> ~/linux/test/python/man/library/math/fsum$ cat main.py
> #!/usr/bin/env python
> print sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
> ~/linux/test/python/man/library/math/fsum$ ./main.py
> 1.0

chris at mbp ~ $ python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = sum(0.1 for i in range(10))
>>> x  # the interpreter implicitly repr()s the result of an expression
0.9999999999999999
>>> print x  # whereas `print` str()s its operands
1.0
>>> (str(x), repr(x))  # as proof and for clarity
('1.0', '0.9999999999999999')

Beware the subtleties of floating-point arithmetic!
http://docs.python.org/tutorial/floatingpoint.html

Cheers,
Chris



More information about the Python-list mailing list