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 130+ updated recipes for modern Python 3.12 with new techniques and tools

Arrow left icon
Product type Paperback
Published in Jul 2024
Publisher Packt
ISBN-13 9781835466384
Length 818 pages
Edition 3rd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Steven F. Lott Steven F. Lott
Author Profile Icon Steven F. Lott
Steven F. Lott
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Chapter 1 Numbers, Strings, and Tuples FREE CHAPTER 2. Chapter 2 Statements and Syntax 3. Chapter 3 Function Definitions 4. Chapter 4 Built-In Data Structures Part 1: Lists and Sets 5. Chapter 5 Built-In Data Structures Part 2: Dictionaries 6. Chapter 6 User Inputs and Outputs 7. Chapter 7 Basics of Classes and Objects 8. Chapter 8 More Advanced Class Design 9. Chapter 9 Functional Programming Features 10. Chapter 10 Working with Type Matching and Annotations 11. Chapter 11 Input/Output, Physical Format, and Logical Layout 12. Chapter 12 Graphics and Visualization with Jupyter Lab 13. Chapter 13 Application Integration: Configuration 14. Chapter 14 Application Integration: Combination 15. Chapter 15 Testing 16. Chapter 16 Dependencies and Virtual Environments 17. Chapter 17 Documentation and Style 18. Other Books You May Enjoy
19. Index

1.2 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.

1.2.1 Getting ready

There are several general cases for division:

  • A div-mod pair: We want both parts – the quotient and the remainder. The name refers to the division and modulo operations combined together. We can summarize the quotient and remainder as q,r = (a b,a mod b).

    We often use this when converting values from one base into another. When we convert seconds into 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, and the remainder will be converted into 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.

1.2.2 How to do it...

We’ll look at these three cases separately.

Doing floor division

When we are doing the div-mod kind of calculations, we might use the floor division operator, //, and the modulo operator, %. The expression a % b gives us the remainder from an integer division of a // b. Or, we might use the divmod() built-in function to compute both at once:

  1. We’ll divide the number of seconds by 3,600 to get the value of hours. The modulo, or remainder in division, computed with the % operator, can be converted separately into minutes and seconds:

    >>> total_seconds = 7385 
     
    >>> hours = total_seconds // 3600 
     
    >>> remaining_seconds = total_seconds % 3600
  2. Next, we’ll divide the number of seconds by 60 to get minutes; the remainder is the 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 to compute quotient and modulo together:

  1. Compute quotient and remainder at the same time:

    >>> total_seconds = 7385 
     
    >>> hours, remaining_seconds = divmod(total_seconds, 3600)
  2. Compute quotient and remainder again:

    >>> minutes, seconds = divmod(remaining_seconds, 60) 
     
    >>> hours, minutes, seconds 
     
    (2, 3, 5)

Doing true division

Performing a true division calculation gives a floating-point approximation as the result. For example, about how many hours is 7,385 seconds? Here’s 736805 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, when using floating-point values, we rounded the result to avoid having to look at tiny error digits.

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)
  2. Use the Fraction value in a calculation. Any integer will be promoted to a Fraction:

    >>> hours = total_seconds / 3600 
     
    >>> hours 
     
    Fraction(1477, 720)

    The denominator of 720 doesn’t seem too meaningful. Working with fractions like this requires a bit of finesse to find useful denominators that makes sense to people. Otherwise, converting to a floating-point value can be useful.

  3. If necessary, convert the exact Fraction into 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 Fraction objects; this promotion means that the math is done as precisely as possible.

1.2.3 How it works...

Python has two division operators:

  • The / true division operator produces 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 preserve the type of the data. The true division operation – when applied to integers – produces a float result.

  • The // truncated division operator always produces a truncated result. For two integer operands, this is the truncated quotient. When floating-point operands are used, this is a truncated floating-point result:

    >>> 7358.0 // 3600.0 
     
    2.0

1.2.4 See also

  • For more on the choice between floating-point and fractions, see the Choosing between float, decimal, and fraction recipe.

  • See PEP-238.

You have been reading a chapter from
Modern Python Cookbook - Third Edition
Published in: Jul 2024
Publisher: Packt
ISBN-13: 9781835466384
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