Avoiding unexpected results with integer division

If you enter only integers when you do arithmetic, Python returns the results in integers. This can give unexpected results if you're doing division with the / operator—you get only the integer part of the result.

TECHNICAL In math terms, the / operator performs floor division, not true STUFF division.

For example, your math teacher would not let you get away with this result:

Tip If you want true division, use one of the following solutions:

• Use the decimal module, like this:

• Decimal("4.333333333333333333333333333")

The decimal module was introduced in Python 2.4. See the section, "Turning Python into a Calculator with decimal," later in this chapter, for details.

• Make sure that at least one of the numbers in a calculation is a floating point (decimal) number, like this:

• 4.333333333333333

Use the division feature from the_future_module,

>>> from future import division >>> 13 / 3~ 4.333333333333333

Using_future_activates code that will become the in this case, it activates true division for the / operator. use the // operator.

Was this article helpful?

0 0

Post a comment