Skip to content Skip to sidebar Skip to footer

Python 3 Floor Division Doesn't Always Result In An Int

When using floor division in python3 (and probably also python2 with import __future__): >>> 2//2 1 the output is an integer as expected. But as soon as one operand is a

Solution 1:

One possible advantage can be the following: If the inputs of an operation are floats, then usually the most useful output type is a float, because the program is doing floating point calculations. Similarly, if the inputs of an operation are integers (ints or longs), then usually the most useful output type is an integer.

A related surprising data point:

>>> str(int(123e300 // 10.0))
'12300000000000000348405169443457756499452463917650245579212965288916278422109198944984236481408634018703901759913201583616648277756338685989513894763895354330869046350917957229381143786183918719192956157930593465276658607709014541611368487360619735051905095032755082564499801643679232993692080863707136'

It's surprising, because it's natural to expect lots of 0s at the end. You get other digits because of the limited precision of the float type.

So by returning a float, // indicates that the output can be inaccurate.

Solution 2:

This makes floor division consistent with the other arithmetic operations. The advantage is that instead of remembering that // is a special case, you can use your existing knowledge and coding patterns. And as with all the other operators, if you want to force the output to be an int you should explicitly coerce it to be such.

Post a Comment for "Python 3 Floor Division Doesn't Always Result In An Int"