Sunday, February 6, 2011

Python: The Division Sign

I've been wrong all these years! I'd always thought 3/2=1.5 . Apparently, it's actually 3/2=1. Much like pi=3 to the Alabama state legislature instead of pi=3.14159... (see the joke).

Clearly this is "wrong" (at least for scientific computing and arguably everywhere else) but here's why this happens. It's the difference in how the data types are defined - the output depends on the input types so

3/2=1 because 3 and 2 are int (integer) type so the output is a truncated integer. This is "floor division" and is how C does it too. However,
3.0/2=1.5 because 3.0 is a float so the output is a float even though 2 is still typed in as an int. I think it's actually a float now too but i'm not sure.

Starting with Python 2.2 a new division operator is introduced. Now
3/2=1.5
3//2=1

The "//" is now the floor division and the single "/" will be true division. I think Python 3 will have this completely integrated but all us 2.x users we're still SOL unless we want to rework all our codes.

Solution: import a module to overwrite the division sign with the upcoming (and computationally relevant) definition. At the very top include the statement

from __future__ import division

now the "/" will always be true division.

This module probably has a bunch of other important stuff. Since i'm learning python right before these all become standards is there a way to import ALL the future commands so I don't have to relearn anything when 3.x if viable for me? Something like from __future__ import * would be nice!

No comments: