Tuesday, June 28, 2011

Curious int/float/division/math 'gotcha' in py (discussion)

So, today I was confused why on earth dividing two ints (which leaves a remainder), didn't return back an int.

In the end, I re-casted the ints as floats, performed the division, and this worked fine.

Looked through the docs, and found this:

"For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value."

Has anyone else come up against this gotcha before? I'm wondering if it's better practise to always cast a number as a float/decimal, rather than an int. 

Any thoughts guys?

Cal


--- code snip ---

>>> import math
>>> math.ceil(7672 / 50)
153.0
>>> 7672 / 50
153
>>> float(7672 / 50)
153.0
>>> 7672 / 50
153
>>> type(7672)
<type 'int'>
>>> type(50)
<type 'int'>
>>> float(7672) / float(50)
153.44
>>> math.ceil(float(7672) / float(50))
154.0
>>>

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment