Problems using modulo

Batista, Facundo FBatista at uniFON.com.ar
Mon Apr 19 12:27:44 EDT 2004


[Brian Gough]

#- > Results:
#- > 5.9 mod 2.0 = 1.9
#- > 6.0 mod 2.0 = 2.0 !!!!!!
#- > 6.1 mod 2.0 = 0.1
#- > 
#- > I don't know much about how Python does its floating point, but it
#- > seems like a bug to me ?
#- 
#- This is a common "feature" of floating-point arithmetic.  
#- 0.1 does not
#- have an exact machine representation in binary, so the numbers
#- displayed are not exact (e.g. 6.0 is actually 5.9999999... with a
#- difference O(10^-15)).  There is an appendix in the Python tutorial
#- which discusses this, with more examples.

You can read also PEP 327 where I propose the Decimal data type, a decimal
floating point.


#- > What is the best workaround so that I can get my code working as
#- > desired ?
#- > (ie I just want to tell whether my time "t" is an exact multiple of
#- > the time interval, 2.0 seconds in this case).
#- 
#- For exact arithmetic, work with integers (e.g. in this case multiply
#- everything 10) or compute the difference from zero in the modulus, d,
#- 
#-   s = t % interval
#-   d = min (s, interval-s)
#- 
#- and compare it with a small tolerance, e.g. 1e-10 or something
#- appropriate to your problem. HTH.

...or work with Decimal.

.	Facundo





. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . .
ADVERTENCIA  

La información contenida en este mensaje y cualquier archivo anexo al mismo,
son para uso exclusivo del destinatario y pueden contener información
confidencial o propietaria, cuya divulgación es sancionada por la ley. 

Si Ud. No es uno de los destinatarios consignados o la persona responsable
de hacer llegar este mensaje a los destinatarios consignados, no está
autorizado a divulgar, copiar, distribuir o retener información (o parte de
ella) contenida en este mensaje. Por favor notifíquenos respondiendo al
remitente, borre el mensaje original y borre las copias (impresas o grabadas
en cualquier medio magnético) que pueda haber realizado del mismo. 

Todas las opiniones contenidas en este mail son propias del autor del
mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones
Personales S.A. o alguna empresa asociada. 

Los mensajes electrónicos pueden ser alterados, motivo por el cual
Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación
cualquiera sea el resultante de este mensaje. 

Muchas Gracias.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20040419/cccf2747/attachment.html>


More information about the Python-list mailing list