Il 12/11/2012 22:10, Daniele Palmese ha scritto:
A dire il vero da me si comporta esattamente al contrario:

Python 2.7.1
Type "help", "copyright", "credits" or "license" for more information.
 >>> a = 12.20
 >>> b = 9.20
 >>> c = 4.20
 >>> a + b + c
25.599999999999998
 >>> print 12.20 + 9.20 + 4.20
25.6

scusate, io sto appena muovendo i primi passi e magari mi sfugge qualcosa... però non mi sembra il contrario di quel che succede a Massimo

il float è arrotondato quando si usa print
quando invece si fa l'addizione è completo

e la spiegazione sta nel link che ho incollato prima:
http://docs.python.org/2/tutorial/floatingpoint.html

e precisamente qui:

It’s easy to forget that the stored value is an approximation to the original decimal fraction, because of the way that floats are displayed at the interpreter prompt. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. If Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display

>>>
>>> 0.1
0.1000000000000000055511151231257827021181583404541015625
That is more digits than most people find useful, so Python keeps the number of digits manageable by displaying a rounded value instead

>>>
>>> 0.1
0.1
It’s important to realize that this is, in a real sense, an illusion: the value in the machine is not exactly 1/10, you’re simply rounding the display of the true machine value. This fact becomes apparent as soon as you try to do arithmetic with these values

>>>
>>> 0.1 + 0.2
0.30000000000000004
Note that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a bug in your code either. You’ll see the same kind of thing in all languages that support your hardware’s floating-point arithmetic (although some languages may not display the difference by default, or in all output modes).
_______________________________________________
Python mailing list
Python@lists.python.it
http://lists.python.it/mailman/listinfo/python

Rispondere a