Integer Division

Hi,

I just stumbled over some unexpected behaviour and thought I’d share it here.

Background: The standard division operator / behaves differently in python 2 and 3. While it performs an integer division in python 2 if both operands are integers, it always performs a true division in python 3.

Now RhinoPython is Python 2.7, so I thought it should behave the “old” way and did a quick test (on SR6):

run_division.py:

import import_division
print 1/3

import_division.py:

print 1/3

Running run_division.py gave me the following output:

0
0.333333333333

So apparently the directly run script uses “new division” while the imported script uses “old division”. This is unexpected to say the least. Tested it on two machines. So if you are getting strange results, have a look at your divisions…

Best

Hanno

If I can remember correctly there was the same issue raised on the old forum.
Due to confusion of new members, Mcneel folks decided to set the a/b resulting in float, even both a and b are integers.

Ah, thank you, that explains it. Python 2 can be forced to act like python 3 by an import statement:

from __future__ import division

So apparently this is what’s implicitely done to executed scripts. Only that it does not affect imported scripts makes things a little inconsistent…

I can’t globally set this for imported scripts or there would be strange errors occurring if you used modules from the standard library that depend on the older integer division style. @djordje is correct; there was a large outpouring of grief over the integer division style which confused many people.

Thanks Steve, I understand that it would break stuff if you set it globally. It’s more that I wasn’t expecting the default behaviour to be overridden at all. I usually implement stuff and then move it into libraries, and it’s not optimal if it suddenly changes behaviour after the relocation… but anyway, now I know why, and I can simply make the setting for my own libraries.