Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Modern Python Cookbook

You're reading from   Modern Python Cookbook The latest in modern Python recipes for the busy modern programmer

Arrow left icon
Product type Paperback
Published in Nov 2016
Publisher Packt
ISBN-13 9781786469250
Length 692 pages
Edition 1st Edition
Languages
Arrow right icon
Toc

Table of Contents (12) Chapters Close

Preface 1. Numbers, Strings, and Tuples 2. Statements and Syntax FREE CHAPTER 3. Function Definitions 4. Built-in Data Structures – list, set, dict 5. User Inputs and Outputs 6. Basics of Classes and Objects 7. More Advanced Class Design 8. Input/Output, Physical Format, and Logical Layout 9. Testing 10. Web Services 11. Application Integration

Choosing between true division and floor division

Python offers us two kinds of division operators. What are they, and how do we know which one to use? We'll also look at the Python division rules and how they apply to integer values.

Getting ready

There are several general cases for doing division:

  • A div-mod pair: We want two parts—the quotient and the remainder. We often use this when converting values from one base to another. When we convert seconds to hours, minutes, and seconds, we'll be doing a div-mod kind of division. We don't want the exact number of hours, we want a truncated number of hours, the remainder will be converted to minutes and seconds.
  • The true value: This is a typical floating-point value—it will be a good approximation to the quotient. For example, if we're computing an average of several measurements, we usually expect the result to be floating-point, even if the input values are all integers.
  • A rational fraction value: This is often necessary when working in American units of feet, inches, and cups. For this, we should be using the Fraction class. When we divide Fraction objects, we always get exact answers.

We need to decide which of these cases apply, so we know which division operator to use.

How to do it...

We'll look at the three cases separately. First we'll look at truncated floor division. Then we'll look at true floating-point division. Finally, we'll look at division of fractions.

Doing floor division

When we are doing the div-mod kind of calculations, we might use floor division, //, and modulus, %. Or, we might use the divmod() function.

  1. We'll divide the number of seconds by 3600 to get the value of hours; the modulus, or remainder, can be converted separately to minutes and seconds:
      >>> total_seconds = 7385
      >>> hours = total_seconds//3600
      >>> remaining_seconds = total_seconds % 3600
  1. Again, using remaining values, we'll divide the number of seconds by 60 to get minutes; the remainder is a number of seconds less than 60:
      >>> minutes = remaining_seconds//60
      >>> seconds = remaining_seconds % 60
      >>> hours, minutes, seconds
      (2, 3, 5)

Here's the alternative, using the divmod() function:

  1. Compute quotient and remainder at the same time:
      >>> total_seconds = 7385
      >>> hours, remaining_seconds = divmod(total_seconds, 3600)
  1. Compute quotient and remainder again:
      >>> minutes, seconds = divmod(remaining_seconds, 60)
      >>> hours, minutes, seconds
      (2, 3, 5)

Doing true division

A true value calculation gives as a floating-point approximation. For example, about how many hours is 7386 seconds? Divide using the true division operator:

>>> total_seconds = 7385
>>> hours = total_seconds / 3600
>>> round(hours,4)
2.0514
We provided two integer values, but got a floating-point exact result. Consistent with our previous recipe for using floating-point values, we rounded the result to avoid having to look at tiny error values.

This true division is a feature of Python 3. We'll look at this from a Python 2 perspective in the next sections.

Rational fraction calculations

We can do division using Fraction objects and integers. This forces the result to be a mathematically exact rational number:

  1. Create at least one Fraction value:
      >>> from fractions import Fraction
      >>> total_seconds = Fraction(7385)
  1. Use the Fraction value in a calculation. Any integer will be promoted to a Fraction:
      >>> hours = total_seconds / 3600
      >>> hours
      Fraction(1477, 720)
  1. If necessary, convert the exact fraction to a floating-point approximation:
      >>> round(float(hours),4)
      2.0514

First, we created a Fraction object for the total number of seconds. When we do arithmetic on fractions, Python will promote any integers to be fractions; this promotion means that the math is done as exactly as possible.

How it works...

Python 3 has two division operators.

  • The / true division operator always tries to produce a true, floating-point result. It does this even when the two operands are integers. This is an unusual operator in this respect. All other operators try to preserve the type of the data. The true division operation - when applied to integers - produces a float result.
  • The // truncated division operator always tries to produce a truncated result. For two integer operands, this is the truncated quotient. For two floating-point operands, this is a truncated floating-point result:
      >>> 7358.0 // 3600.0
      2.0

By default, Python 2 only has one division operator. For programmers still using Python 2, we can start using these new division operators with this:

>>> from __future__ import division

This import will install the Python 3 division rules.

See also

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image