[Tutor] Hummm...dubious behavior.

Gregor Lingl glingl@aon.at
Thu Nov 15 16:18:16 CET 2012


Jean Montambeault schrieb:

    Felt ready for Guido's idea of a tutorial, tryed the examples, tryed
some variations, can't help it and here's something curious :
> >>> tax=17.5/100
> >>> price=3.50
> >>> price*tax
> 0.61249999999999993
> >>> price+_
> 4.1124999999999998
> >>> round(_,2)
> 4.1100000000000003    # in this case : trailing zeros and an error
> ...
> Obviously my question is what caused the difference in behavior, when must I
> expect it or best how to avoid it since, really, I can't imagine a use for
> the "long" version..

Dear Jean!

I also noticed that there are those things in the Python Tutorial, which
do not coincide with the Python - reality. (This is really a little bit
disturbing for beginners - and should be corrected some time).

As far as I know, the representation

>>> 0.6125
0.61250000000000004
>>>

occurs because of the fact, that the number 0.6125 is not a power of 2
(or 1/2) and so the internal binary representation of it *has* to be
an approximation of it.

This is reflected in the output of the Python-evaluator, which
delivers some 'raw' form of the result of evaluation in contrast
to the print - statement:

>>> print 0.6125
0.6125
>>>

(However, operating this way prevents you from using _ )

(You can observe this difference also here:

>>> 'python'
'python'
>>> print 'python'
python
>>>                                                            )

The print-statement obviously polishes the output
into a form, which is more user-friendly.

(Maybe this has something to do with the difference
between __repr__ and __str__   (?) )

On the other hand one can find inconsistencies (in
my opinion) even concerning this point, for example:

>>> print 0.6125, 4.1225
0.6125 4.1225                                                # but:
>>> print (0.6125, 4.1225)
(0.61250000000000004, 4.1224999999999996)
>>>

Some deeper explanations are welcome

Gregor




More information about the Tutor mailing list