Tuesday, June 28, 2011

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

Yeah I'm aware of this now, but it was more of a "oh, didn't ever notice this before" rather than a "why is this happening" thread :)

I was expecting that dividing two ints would return a float, but it doesn't. It does make sense, just a bit of a gotcha, you know?

Cal

On Tue, Jun 28, 2011 at 2:31 PM, Tom Evans <tevans.uk@googlemail.com> wrote:
On Tue, Jun 28, 2011 at 2:23 PM, Cal Leeming [Simplicity Media Ltd]
<cal.leeming@simplicitymedialtd.co.uk> wrote:
> 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:
> http://docs.python.org/library/stdtypes.html
> "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

Bit OT, but I'll bite (doesn't really relate to Django). Dividing two
ints ALWAYS returns an int. Calling math.ceil() ALWAYS returns a
float. I think you were expecting that python would automagically
store the remainder somewhere so that math.ceil() has something to
operate on. It doesn't do that!

If you wish to do rounding, convert either operand to a float. The
'Note that the result is a long integer if either operand is a long
integer' is referring to dividing two integral types - if either is a
long, the result will be a long. It doesn't apply if either operand is
a float, eg if you divide a float by a long, the result is a float,
not a long.

Cheers

Tom

--
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.


--
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