Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

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

14 views
Skip to first unread message

Peng Yu

unread,
Jul 6, 2012, 6:38:38 PM7/6/12
to
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

Regards,
Peng

Chris Rebert

unread,
Jul 6, 2012, 6:59:28 PM7/6/12
to Peng Yu, pytho...@python.org
chris@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
0 new messages