Computer Science · Book 2 · Grades 10–12

High School Computer Science

High School Computer Science · Grades 10–12

23Classes and Objects

A date is three numbers: a year, a month, a day. But adding one day to 28 February is not adding one to the third number: it gives 29 February or 1 March, depending on the year, and 31 December gives a new year. A date is three numbers and the rules that go with them. If the numbers travel through a program without their rules, sooner or later some function forgets one, and the 30th of February appears.

Python lets a program define its own kinds of values, which carry their data and the functions that respect their rules together. This chapter defines such classes, protects their rules, gives them the operators of the language, derives one class from another, and closes on the different styles in which the same program can be written.

You already know

A module offers an interface and hides its implementation (chapter 20). A list is mutable: two names can refer to the same list (chapter 2). The town library’s loans table (chapter 7).

23.1 Grouping data with the functions that act on it

Definition 23.1 (Class, instance, attribute, method)

A class is a new type of value, defined by the program. A value of that type is an instance of the class, also called an object. Each instance holds named values, its attributes; the functions defined in the class, which act on an instance, are its methods.

Definition 23.2 (Constructor)

The constructor of a class is the method that gives a new instance its first attributes. In Python it is named __init__, and it runs when the class is called: Point(3, 4).

A method receives the instance it acts on as its first parameter, by convention named self: a.distance_to(b) is the call Point.distance_to(a, b).

import math


class Point:
    """A point of the plane."""

    def __init__(self, x, y):          # the constructor: sets the attributes
        self.x = x
        self.y = y

    def distance_to(self, other):
        return math.hypot(self.x - other.x, self.y - other.y)

    def move(self, dx, dy):
        self.x += dx
        self.y += dy


a, b = Point(0, 0), Point(3, 4)
print(a.distance_to(b))                # Point.distance_to(a, b)
c = b
c.move(1, 1)                           # c and b are the same object
print(b.x, b.y, "| same object:", b is c)
d = Point(4, 5)
print("equal coordinates:", d.x == b.x and d.y == b.y, "| same object:", d is b)
print(type(a).__name__, isinstance(a, Point))
Listing 23.1. A class of points, three instances, and two names for one object. code/grade-12/02-classes-and-objects/listings/point_class.py
$ python point_class.py
5.0
4 5 | same object: True
equal coordinates: True | same object: False
Point True
Output 23.1. Moving c moved b: they are one object. d has the same coordinates, but is another object.
One class, three objects. The class holds the methods once; each object holds its own attributes. Two names, b and c, refer to the same object; d is a different object with equal values.
One class, three objects. The class holds the methods once; each object holds its own attributes. Two names, b and c, refer to the same object; d is a different object with equal values.

23.2 Encapsulation and the interface of a class

Definition 23.3 (Encapsulation, class invariant)

Encapsulation is keeping an object’s attributes behind its methods: users call the methods, which are the class’s interface, and leave the attributes alone. A class invariant is a property of the attributes that the constructor establishes and every method keeps.

A fraction is kept reduced, with a positive denominator: 6/86/8 is stored as 3/43/4 and 1/(−3)1/(-3) as −1/3-1/3. The constructor reduces by the greatest common divisor (the mathematics book), and every operation builds its result through the constructor, so the invariant holds for every fraction ever made. The attributes start with an underscore: they are internal, as in a module (chapter 20).

"""Exact fractions, always reduced, with a positive denominator."""
import math


class Fraction:
    def __init__(self, num, den=1):
        if den == 0:
            raise ZeroDivisionError("a fraction with denominator 0")
        g = math.gcd(num, den)
        if den < 0:                     # the sign goes to the numerator
            g = -g
        self._num = num // g            # invariant: gcd(num, den) = 1 and den > 0
        self._den = den // g

    def numerator(self):
        return self._num

    def denominator(self):
        return self._den
Listing 23.2. Fractions: the constructor establishes the invariant. code/grade-12/02-classes-and-objects/listings/fraction.py

The rest of the class is a set of special methods, explained in the next section.

    def __repr__(self):
        return f"Fraction({self._num}, {self._den})"

    def __str__(self):
        return str(self._num) if self._den == 1 else f"{self._num}/{self._den}"

    def __eq__(self, other):
        return self._num == other._num and self._den == other._den

    def __lt__(self, other):
        return self._num * other._den < other._num * self._den

    def __add__(self, other):
        return Fraction(self._num * other._den + other._num * self._den,
                        self._den * other._den)

    def __mul__(self, other):
        return Fraction(self._num * other._num, self._den * other._den)

    def __float__(self):
        return self._num / self._den
Listing 23.3. Fractions: printing, comparing, adding, multiplying. code/grade-12/02-classes-and-objects/listings/fraction.py
from fraction import Fraction

a, b = Fraction(6, 8), Fraction(1, -3)
print(a, b, repr(a))
print(a + b, a * b, a + b == Fraction(5, 12))
print(sorted([Fraction(2, 3), Fraction(1, 2), Fraction(3, 5)]))
print(float(Fraction(1, 3)), Fraction(10, 5))
try:
    Fraction(1, 0)
except ZeroDivisionError as error:
    print("ZeroDivisionError:", error)
Listing 23.4. Using the class: two fractions, their sum and product, a sort, a conversion, and a denominator 00. code/grade-12/02-classes-and-objects/listings/use_fraction.py
$ python use_fraction.py
3/4 -1/3 Fraction(3, 4)
5/12 -1/4 True
[Fraction(1, 2), Fraction(3, 5), Fraction(2, 3)]
0.3333333333333333 2
ZeroDivisionError: a fraction with denominator 0
Output 23.2. Every result is reduced; a denominator 00 is refused at once.

The class Date keeps a stronger invariant: its three numbers always form a real date. The constructor refuses anything else, and next_day handles the month and year changes in one place.

"""Dates of the calendar, always valid."""


def is_leap(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)


def days_in_month(year, month):
    if month == 2:
        return 29 if is_leap(year) else 28
    return 30 if month in (4, 6, 9, 11) else 31


class Date:
    def __init__(self, year, month, day):
        if not (1 <= month <= 12 and 1 <= day <= days_in_month(year, month)):
            raise ValueError(f"no such date: {year}-{month}-{day}")
        self._ymd = (year, month, day)          # invariant: a real date

    def __str__(self):
        return "{:04}-{:02}-{:02}".format(*self._ymd)

    def __eq__(self, other):
        return self._ymd == other._ymd

    def __lt__(self, other):
        return self._ymd < other._ymd           # tuples compare year first

    def next_day(self):
        year, month, day = self._ymd
        if day < days_in_month(year, month):
            return Date(year, month, day + 1)
        if month < 12:
            return Date(year, month + 1, 1)
        return Date(year + 1, 1, 1)
Listing 23.5. Dates that are always valid. code/grade-12/02-classes-and-objects/listings/date_class.py
from date_class import Date

for d in [Date(2026, 3, 14), Date(2028, 2, 28), Date(2027, 2, 28), Date(2026, 12, 31)]:
    print(d, "->", d.next_day())
print(Date(2026, 1, 31) < Date(2026, 2, 1), Date(2026, 5, 1) == Date(2026, 5, 1))
for bad in [(2027, 2, 29), (2026, 13, 1), (2026, 4, 31)]:
    try:
        Date(*bad)
    except ValueError as error:
        print("ValueError:", error)
Listing 23.6. Using Date: four days after, two comparisons, three impossible dates. code/grade-12/02-classes-and-objects/listings/use_date.py
$ python use_date.py
2026-03-14 -> 2026-03-15
2028-02-28 -> 2028-02-29
2027-02-28 -> 2027-03-01
2026-12-31 -> 2027-01-01
True True
ValueError: no such date: 2027-2-29
ValueError: no such date: 2026-13-1
ValueError: no such date: 2026-4-31
Output 23.3. The day after four dates, two comparisons, and three dates refused.

Python does not lock the attributes. A program that writes into _num breaks the invariant, and with it the methods that rely on it.

from fraction import Fraction

half = Fraction(1, 2)
half._num = 2                       # reaching inside: the invariant is broken
print(half, "| equal to 1?", half == Fraction(1, 1))
print("half + half =", half + half)
Listing 23.7. Reaching inside an object. code/grade-12/02-classes-and-objects/listings/bad_mutation.py
$ python bad_mutation.py
2/2 | equal to 1? False
half + half = 2
Output 23.4. A “fraction” 2/22/2, not equal to 11: __eq__ assumed the invariant.

Remark 23.4

Python also offers properties: an attribute that is read like f.numerator but computed by a method, which can refuse to be written. They let a class change how it stores its data without changing how users read it.

23.3 Special methods

Definition 23.5 (Special method)

A special method is a method with a name of the form __name__ that Python calls by itself for an operation of the language: __add__ for +, __eq__ for ==, __lt__ for <, __len__ for len, __str__ for str and print, __repr__ for the form shown in lists and for programmers.

class Duration:
    """A length of time, in whole minutes."""

    def __init__(self, minutes):
        self.minutes = minutes

    def __repr__(self):                   # for programmers: how to rebuild it
        return f"Duration({self.minutes})"

    def __str__(self):                    # for people
        return f"{self.minutes // 60} h {self.minutes % 60:02}"

    def __eq__(self, other):
        return self.minutes == other.minutes

    def __lt__(self, other):
        return self.minutes < other.minutes

    def __add__(self, other):
        return Duration(self.minutes + other.minutes)


class Playlist:
    def __init__(self, name, durations):
        self.name, self.durations = name, list(durations)

    def __len__(self):
        return len(self.durations)


songs = [Duration(4), Duration(71), Duration(12)]
print(songs, "|", songs[1])
print(sorted(songs), max(songs), Duration(4) == Duration(4))
print(sum(songs, Duration(0)))
print(len(Playlist("morning", songs)))
Listing 23.8. Durations that print, compare, sort and add. code/grade-12/02-classes-and-objects/listings/special_methods.py
$ python special_methods.py
[Duration(4), Duration(71), Duration(12)] | 1 h 11
[Duration(4), Duration(12), Duration(71)] 1 h 11 True
1 h 27
3
Output 23.5. A list shows repr, print shows str; sorted and max use <; sum uses +.

23.4 Inheritance, a first look

Definition 23.6 (Inheritance, subclass, overriding)

A subclass is a class defined from another, its base class, by inheritance: it has all the base class’s methods, and may add others. A method of the subclass with the same name as one of the base class overrides it: it replaces it for the instances of the subclass.

import math


class Shape:
    def area(self):
        raise NotImplementedError("each kind of shape gives its own area")

    def describe(self):                   # inherited by every subclass
        return f"{type(self).__name__} of area {self.area():.2f}"


class Rectangle(Shape):
    def __init__(self, width, height):
        self.width, self.height = width, height

    def area(self):                       # overrides Shape.area
        return self.width * self.height


class Square(Rectangle):
    def __init__(self, side):
        super().__init__(side, side)      # the constructor of Rectangle


class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2


for shape in [Rectangle(3, 2), Square(4), Circle(1)]:
    print(shape.describe(), "| a Rectangle?", isinstance(shape, Rectangle))
Listing 23.9. A base class, three subclasses, and super(). code/grade-12/02-classes-and-objects/listings/shapes.py
$ python shapes.py
Rectangle of area 6.00 | a Rectangle? True
Square of area 16.00 | a Rectangle? True
Circle of area 3.14 | a Rectangle? False
Output 23.6. describe is written once and calls the right area for each shape; a square is a rectangle.
The classes of shapes.py. An arrow goes from a subclass to its base class. describe is inherited by all; area is overridden; Square only changes the constructor, through super().
The classes of shapes.py. An arrow goes from a subclass to its base class. describe is inherited by all; area is overridden; Square only changes the constructor, through super().

Inheritance suits an “is a” relation: a square is a rectangle. It is a poor tool for sharing code between classes that are not of the same kind; then an object that holds another (a playlist holds durations) is clearer.

23.5 Programming paradigms

Definition 23.7 (Programming paradigm)

A programming paradigm is a style of writing programs. In the imperative style, a program is a sequence of instructions that change variables. In the functional style, it is built from functions applied to values, without changing variables. In the object style, it is organised around objects that hold data and the methods acting on it.

Definition 23.8 (Pure function)

A pure function is a function whose result depends only on its arguments and which changes nothing outside itself: no global variable, no attribute, no printing, no file.

The town library wants the total number of days late over the loans returned after their due date. The same program three times:

"""Total days late over the loans returned after their due date, three ways."""
import csv
from datetime import date

with open("loans.csv", newline="") as f:
    LOANS = list(csv.DictReader(f))


def days(a, b):
    return (date.fromisoformat(b) - date.fromisoformat(a)).days


def is_late(loan):
    return loan["return_date"] != "" and loan["return_date"] > loan["due_date"]


# imperative: a variable changed step by step
total = 0
for loan in LOANS:
    if is_late(loan):
        total += days(loan["due_date"], loan["return_date"])
print("imperative:", total)

# functional: functions applied to whole sequences, no variable changed
lateness = map(lambda x: days(x["due_date"], x["return_date"]), filter(is_late, LOANS))
print("functional:", sum(lateness))


# object: each loan knows how late it is
class Loan:
    def __init__(self, row):
        self.due, self.returned = row["due_date"], row["return_date"]

    def days_late(self):
        if self.returned != "" and self.returned > self.due:
            return days(self.due, self.returned)
        return 0


print("object:", sum(Loan(row).days_late() for row in LOANS))
Listing 23.10. Days late, imperative, functional and object. code/grade-12/02-classes-and-objects/listings/paradigms.py
$ python paradigms.py
imperative: 1371
functional: 1371
object: 1371
Output 23.7. Three styles, one answer.
The same computation in three styles. Real programs mix them: the object version uses a functional sum, and the methods of a class are often written imperatively.
The same computation in three styles. Real programs mix them: the object version uses a functional sum, and the methods of a class are often written imperatively.

Each style has its field. The functional style makes programs easy to test and to run in parallel, since pure functions cannot disturb one another. The object style suits programs with many kinds of things, each with its own rules: windows and buttons, accounts, the pieces of a game. The imperative style is the closest to the machine, and often the most direct for a short computation.

23.6 Exercises

Exercise 23.1 ★

What does print(Point(1, 2)) show, with the class of the chapter? How can it be made to show (1, 2)?

Solution

Solution of Exercise 23.1.

Something like <__main__.Point object at 0x7f3a...>: the class name and a memory address, which changes from run to run. Defining a special method gives a readable form:

def __repr__(self):

return f"({self.x}, {self.y})"

Without __str__, print uses __repr__.

Exercise 23.2 ★

After a = Fraction(1, 2), b = a + Fraction(1, 4) and c = b * Fraction(2, 3), what do print(b, c) and print(repr(c)) show?

Solution

Solution of Exercise 23.2.

b=12+14=34b = \frac12 + \frac14 = \frac34 and c=34×23=612=12c = \frac34 \times \frac23 = \frac{6}{12} = \frac12: print(b, c) shows 3/4 1/2, and print(repr(c)) shows Fraction(1, 2).

Exercise 23.3 ★

Write a class Tally with a method add(k=1), which adds k to a count starting at 00, and a method value().

Solution

Solution of Exercise 23.3.

class Tally:

def __init__(self):

self._count = 0

def add(self, k=1):

self._count += k

def value(self):

return self._count

Exercise 23.4 ★

p = Point(1, 2), q = p, q.move(2, 0), r = Point(p.x, p.y), r.move(0, 1). Give the coordinates of p, q and r.

Solution

Solution of Exercise 23.4.

p and q are one object, moved once: both are at (3,2)(3, 2). r is a new object built from those values, then moved: (3,3)(3, 3); moving it changed neither p nor q.

Exercise 23.5 ★

A student writes def move(dx, dy): in the class Point. The call p.move(1, 1) raises TypeError: Point.move() takes 2 positional arguments but 3 were given. Explain the three.

Solution

Solution of Exercise 23.5.

p.move(1, 1) is the call Point.move(p, 1, 1): three arguments, the object and the two numbers. The method was written with two parameters, as if Python did not pass the object. The repair is def move(self, dx, dy):; without it, even the body could not name the object it should change.

Exercise 23.6 ★★

Write sub(a, b), the difference of two fractions, using only the interface of Fraction. Why is the result reduced without any work of yours?

Solution

Solution of Exercise 23.6.

def sub(a, b):

num = a.numerator() * b.denominator() - b.numerator() * a.denominator()

return Fraction(num, a.denominator() * b.denominator())

The result is built by the constructor, which reduces it: the invariant is the class’s work, not the user’s. sub(Fraction(1, 2), Fraction(1, 3)) is 1/6.

Exercise 23.7 ★★

{Fraction(1, 2)} raises TypeError: unhashable type: 'Fraction'. Why can an object with __eq__ not go into a set, until the class also defines __hash__?

Solution

Solution of Exercise 23.7.

A set finds its elements by their hash, and equal elements must have equal hashes, or two equal fractions could sit in two places of the same set. The hash Python gives every object by default comes from its identity: two equal fractions, being two objects, would get different hashes. So a class that defines __eq__ loses that default, and its objects are refused by sets and as dictionary keys until it defines __hash__ from the values it compares, for example return hash((self._num, self._den)). This is only safe because no method changes a fraction once built.

Exercise 23.8 ★★

A.__init__ prints A. B(A) has an __init__ that prints B in, calls super().__init__(), then prints B out. What does B() print? And without the call to super()?

Solution

Solution of Exercise 23.8.

B in, A, B out: super().__init__() runs the constructor of A in the middle of that of B. Without the call, B in and B out only: the constructor of A never runs, and any attribute it would have set is missing from the object.

Exercise 23.9 ★★

Write a method previous_day for the class Date, and check it on 1 March 2028 and 1 January 2027.

Solution

Solution of Exercise 23.9.

def previous_day(self):

year, month, day = self._ymd

if day > 1:

return Date(year, month, day - 1)

if month > 1:

return Date(year, month - 1, days_in_month(year, month - 1))

return Date(year - 1, 12, 31)

1 March 2028 gives 2028-02-29, a leap year; 1 January 2027 gives 2026-12-31. The tests compare the method with the calendar of the standard library on 12001200 days in a row.

Exercise 23.10 ★★

Prove that every Fraction, including the results of + and *, has a positive denominator and a numerator and denominator with no common divisor other than 11.

Solution

Solution of Exercise 23.10.

Every fraction is made by the constructor, since + and * return Fraction(...). So it is enough to check the constructor, for any numerator aa and denominator b≠0b \ne 0. Let g=gcd⁡(a,b)g = \gcd(a, b), positive since b≠0b \ne 0. The divisions a/ga / g and b/gb / g are exact, and two numbers divided by their greatest common divisor have no common divisor other than 11: a common divisor d>1d > 1 of a/ga/g and b/gb/g would make dgdg a common divisor of aa and bb larger than gg. If b<0b < 0, both are divided by −g-g instead: the signs change, the common divisors do not, and the denominator b/(−g)b / (-g) is positive. For + and *, the denominator passed is the product of two positive denominators, never 00, so the constructor accepts it and the argument applies.

Exercise 23.11 ★★

Rewrite in the functional style, with filter, map and sum: total = 0, then for x in t:, if x % 2 == 0:, total += x * x.

Solution

Solution of Exercise 23.11.

total = sum(map(lambda x: x * x, filter(lambda x: x % 2 == 0, t)))

or, with a comprehension, sum(x * x for x in t if x % 2 == 0). For t = range(7): 0+4+16+36=560 + 4 + 16 + 36 = 56.

Exercise 23.12 ★★★

Write a class Stack with push, pop, peek, is_empty and len, where pop and peek raise IndexError on an empty stack, and tests for it.

Solution

Solution of Exercise 23.12.

class Stack:

def __init__(self):

self._items = []

def push(self, x):

self._items.append(x)

def pop(self):

if not self._items:

raise IndexError("pop from an empty stack")

return self._items.pop()

def peek(self):

if not self._items:

raise IndexError("peek at an empty stack")

return self._items[-1]

def is_empty(self):

return self._items == []

def __len__(self):

return len(self._items)

Tests: after pushing 11 then 22, pop() returns 22, then peek() returns 11 and len is 11; a new stack is empty, and pop() on it raises IndexError (checked with assertRaises). The next chapter builds stacks without Python’s list.

Exercise 23.13 ★★★

How many Fraction objects does this program create? total = Fraction(0), then for kk from 11 to 44, total = total + Fraction(1, k). How many are still reachable at the end?

Solution

Solution of Exercise 23.13.

Nine: Fraction(0), then at each of the four turns Fraction(1, k) and the result of +, made by __add__. At the end only one is reachable, the one named total, 25/1225/12; the eight others are no longer named by anything, and Python frees their memory.

Exercise 23.14 ★★★

A class Basket has the line items = [] in its body, outside any method, and a method add that appends to self.items. After a.add("pear"), the basket b also holds a pear. Explain and correct.

Solution

Solution of Exercise 23.14.

items = [] in the body of the class makes one list, an attribute of the class itself. self.items looks for an attribute of the object, finds none, and finds the class’s: every basket appends to the same list. The repair gives each object its own list in the constructor:

def __init__(self):

self.items = []

Exercise 23.15 ★★★

Write a class Polynomial built from its list of coefficients [a0,a1,… ][a_0, a_1, \dots], with __add__, __mul__, and __call__ so that p(x) computes the value at x.

Solution

Solution of Exercise 23.15.

class Polynomial:

def __init__(self, coefficients):

c = list(coefficients)

while len(c) > 1 and c[-1] == 0:

c.pop()

self.c = c

def __add__(self, other):

n = max(len(self.c), len(other.c))

a = self.c + [0] * (n - len(self.c))

b = other.c + [0] * (n - len(other.c))

return Polynomial([x + y for x, y in zip(a, b)])

def __mul__(self, other):

out = [0] * (len(self.c) + len(other.c) - 1)

for i, x in enumerate(self.c):

for j, y in enumerate(other.c):

out[i + j] += x * y

return Polynomial(out)

def __call__(self, x):

result = 0

for a in reversed(self.c):

result = result * x + a

return result

The constructor drops the zero coefficients at the end, so that (1+x)2−x2(1 + x)^2 - x^2 is stored as [1, 2]. The term xix^i times xjx^j goes to xi+jx^{i+j}. __call__ evaluates from the highest coefficient down, one multiplication per coefficient: (1+x)2(1 + x)^2 at 22 gives 99.

23.7 Problem: Exact Fractions

Problem 23.1

Weekend problem — the harmonic sums, exactly

The harmonic sums are Hn=1+12+13+⋯+1nH_n = 1 + \frac12 + \frac13 + \dots + \frac1n. With the class Fraction, a program computes them exactly, compares their denominators with the least common multiple of 1,…,n1, \dots, n, and measures the error of the same sums in floating point.

"""The harmonic sums 1 + 1/2 + ... + 1/n, exactly and in floating point."""
import math

from fraction import Fraction

exact, approx = Fraction(0), 0.0
for n in range(1, 1001):
    exact = exact + Fraction(1, n)
    approx += 1 / n
    if n <= 10 or n in (15, 20):
        lcm = math.lcm(*range(1, n + 1))
        print(f"H{n:<2} = {str(exact):>18}   lcm(1..{n}) = {lcm:>8}"
              f" = {lcm // exact.denominator()} x denominator")
    if n in (10, 100, 1000):
        print(f"  n = {n:4}: float sum {approx!r:<20} exact value {float(exact)!r:<20}"
              f" error {approx - float(exact):.1e}")
print("digits of the exact numerator for n = 1000:", len(str(exact.numerator())))
Listing 23.11. Harmonic sums exact and in floating point. code/grade-12/02-classes-and-objects/listings/harmonic.py
$ python harmonic.py
H1  =                  1   lcm(1..1) =        1 = 1 x denominator
H2  =                3/2   lcm(1..2) =        2 = 1 x denominator
H3  =               11/6   lcm(1..3) =        6 = 1 x denominator
H4  =              25/12   lcm(1..4) =       12 = 1 x denominator
H5  =             137/60   lcm(1..5) =       60 = 1 x denominator
H6  =              49/20   lcm(1..6) =       60 = 3 x denominator
H7  =            363/140   lcm(1..7) =      420 = 3 x denominator
H8  =            761/280   lcm(1..8) =      840 = 3 x denominator
H9  =          7129/2520   lcm(1..9) =     2520 = 1 x denominator
H10 =          7381/2520   lcm(1..10) =     2520 = 1 x denominator
  n =   10: float sum 2.9289682539682538   exact value 2.9289682539682538   error 0.0e+00
H15 =     1195757/360360   lcm(1..15) =   360360 = 1 x denominator
H20 =  55835135/15519504   lcm(1..20) = 232792560 = 15 x denominator
  n =  100: float sum 5.187377517639621    exact value 5.187377517639621    error 0.0e+00
  n = 1000: float sum 7.485470860550343    exact value 7.485470860550345    error -1.8e-15
digits of the exact numerator for n = 1000: 434
Output 23.8. The exact sums, their denominators, and three comparisons with floating point.

Part I — A class of fractions.

  1. Which attributes does a Fraction have, and why do their names start with an underscore?
  2. What does Fraction(10, -4) store?
  3. Which special method does exact + Fraction(1, n) call, and with which arguments?
  4. Why does Fraction(1, 2) == Fraction(2, 4) hold, although 2/42/4 was written?
  5. Why does the class define numerator() and denominator() rather than letting users read _num and _den?

Part II — The invariant.

  1. State the invariant of Fraction.
  2. Prove that the constructor establishes it, whatever the signs of its arguments (the denominator not 00).
  3. Show that __eq__ is right because of the invariant: two fractions are equal numbers exactly when their reduced forms are equal.
  4. What does bad_mutation.py show about Python’s protection of attributes?

Part III — The harmonic sums exactly.

  1. Compute H4H_4 by hand, and check the output.
  2. From the output, give H9H_9 and H10H_{10}. Check H10=H9+110H_{10} = H_9 + \frac{1}{10}.
  3. How many digits has the numerator of H1000H_{1000}? Why could no type of fixed size hold it?
  4. Why can no floating-point number hold H3=11/6H_3 = 11/6 exactly?

Part IV — Denominators and floating point.

  1. Why is lcm⁡(1,…,n)\operatorname{lcm}(1, \dots, n) always a common denominator of the terms of HnH_n?
  2. For which nn of the output is the reduced denominator smaller than that common multiple? By how much?
  3. For n=6n = 6, write H6H_6 over 6060 and explain why it reduces by 33.
  4. At n=10n = 10 and n=100n = 100, how large is the floating-point error printed? And at n=1000n = 1000?
  5. Where does that error come from? Recall chapter 4.
  6. Why is the error at n=1000n = 1000 so small compared with the value?
  7. State the result: H10H_{10} exactly, and the error of the floating-point sum up to 10001000.
Solution

Solution of Problem 23.1.

1. _num and _den. The underscore says they are internal: users go through the methods, which keep the invariant.

2. gcd⁡(10,−4)=2\gcd(10, -4) = 2; the denominator is negative, so both are divided by −2-2: _num is −5-5 and _den is 22.

3. __add__, with self the fraction named exact and other the new Fraction(1, n).

4. The constructor stored 2/42/4 as 1/21/2; __eq__ then compares 11 with 11 and 22 with 22.

5. The methods give read access only, so that no user can break the invariant by writing; and the class stays free to store its data otherwise without changing its users.

6. The denominator is positive, and the numerator and denominator have no common divisor other than 11.

7. Exercise 23.10.

8. Let a/ba/b and c/dc/d be reduced, with b,d>0b, d > 0. If they are equal numbers, ad=bcad = bc. Then bb divides adad and has no common divisor with aa, so bb divides dd; in the same way dd divides bb. Both being positive, b=db = d, and then a=ca = c. Equal numbers have equal attributes, so comparing attributes is right; without the invariant, 1/21/2 and 2/42/4 would be found different.

9. That it does not protect them: the underscore is a convention, and any program can write half._num = 2. The invariant breaks, and __eq__, which relies on it, answers wrongly that 2/22/2 is not 11.

10. 1212+612+412+312=2512\frac{12}{12} + \frac{6}{12} + \frac{4}{12} + \frac{3}{12} = \frac{25}{12}, as printed.

11. H9=7129/2520H_9 = 7129/2520 and H10=7381/2520H_{10} = 7381/2520; 110=2522520\frac{1}{10} = \frac{252}{2520}, and 7129+252=73817129 + 252 = 7381.

12. 434434 digits. A 6464-bit integer holds at most 264−12^{64} - 1, which has 2020 digits; Python’s integers grow as needed (chapter 3).

13. A floating-point number is a whole number of at most 5353 bits times a power of 22 (chapter 4): its denominator is a power of 22. 11/611/6 has the factor 33 in its reduced denominator, so its binary writing never ends, and every floating-point number differs from it.

14. Each kk from 11 to nn divides lcm⁡(1,…,n)\operatorname{lcm}(1, \dots, n), so 1k\frac1k is the fraction with that denominator and numerator lcm⁡(1,…,n)/k\operatorname{lcm}(1, \dots, n) / k, a whole number.

15. For n=6n = 6, 77 and 88, by a factor 33; for n=20n = 20, by a factor 1515. For the other printed values the reduced denominator is the common multiple itself.

16. lcm⁡(1,…,6)=60\operatorname{lcm}(1, \dots, 6) = 60, and H6=60+30+20+15+12+1060=14760H_6 = \frac{60 + 30 + 20 + 15 + 12 + 10}{60} = \frac{147}{60}. 147=3×49147 = 3 \times 49 and 60=3×2060 = 3 \times 20: H6=49/20H_6 = 49/20.

17. 00 at n=10n = 10 and n=100n = 100: the floating-point sum is the closest floating-point number to the exact value. At n=1000n = 1000, −1.8×10−15-1.8 \times 10^{-15}.

18. Each addition rounds its result to the nearest floating-point number, and 1/k1/k is itself rounded; the small errors of a thousand roundings mostly cancel out, but not all of them: a few units of the last place remain.

19. The value is about 7.497.49, so the error is about 2.4×10−162.4 \times 10^{-16} of it: two units of the last bit for numbers between 44 and 88, whose spacing is 2−50≈8.9×10−162^{-50} \approx 8.9 \times 10^{-16}. Fifteen significant digits are right.

20. H10=7381/2520H_{10} = 7381/2520 exactly; summed in floating point up to n=1000n = 1000, the harmonic sum is off by 1.8×10−151.8 \times 10^{-15}, about 2×10−162 \times 10^{-16} of its value 7.485 470 860 550 3457.485\,470\,860\,550\,345.

Terms defined in this chapter

See all 1050 terms in the glossary