12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Division: Classic, Floor, and TrueNow that you’ve seen how division works, you should know that it is scheduled for aslight change in a future <strong>Python</strong> release (currently, 3.0, scheduled to appear sometime after this edition is released). In <strong>Python</strong> 2.5, things work as just described, butthere are actually two different division operators (one of which will change):X/YClassic division. In <strong>Python</strong> 2.5 and earlier, this operator truncates results forintegers, and keeps remainders for floating-point numbers, as described here.This operator will be changed to true division—always keeping remaindersregardless of types—in a future <strong>Python</strong> release (3.0).X// YFloor division. Added in <strong>Python</strong> 2.2, this operator always truncates fractionalremainders down to their floor, regardless of types.Floor division was added to address the fact that the results of the current classicdivision model are dependent on operand types, and so can be difficult to anticipatein a dynamically typed language like <strong>Python</strong>.Due to possible backward-compatibility issues, division in <strong>Python</strong> is in a state of fluxtoday. To recap, in version 2.5, / division works as described by default, and // floordivision can be used to truncate result remainders to their floor regardless of theirtypes:>>> (5 / 2), (5 / 2.0), (5 / -2.0), (5 / -2)(2, 2.5, -2.5, -3)>>> (5 // 2), (5 // 2.0), (5 // -2.0), (5 // -2)(2, 2.0, -3.0, -3)>>> (9 / 3), (9.0 / 3), (9 // 3), (9 // 3.0)(3, 3.0, 3, 3.0)In a future <strong>Python</strong> release, / division is slated to be changed to return a true divisionresult that always retains remainders, even for integers—for example, 1/2will be 0.5,not 0, while 1//2 will still be 0.Until this change is incorporated completely, you can see the way that the / operatorwill likely work in the future by using a special import of the form: from _ _future_ _import division. This turns the / operator into a true division operator (keepingremainders), but leaves // as is. Here’s how / will eventually behave:>>> from _ _future_ _ import division>>> (5 / 2), (5 / 2.0), (5 / -2.0), (5 / -2)(2.5, 2.5, -2.5, -2.5)>>> (5 // 2), (5 // 2.0), (5 // -2.0), (5 // -2)(2, 2.0, -3.0, -3)102 | Chapter 5: Numbers

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!