Simple numerical recursions

We can consider all numeric operations to be defined by recursions. For more details, read about the Peano axioms that define the essential features of numbers at: http://en.wikipedia.org/wiki/Peano_axioms.

From these axioms, we can see that addition is defined recursively using more primitive notions of the next number, or successor of a number, n.

To simplify the presentation, we'll assume that we can define a predecessor function, , such that , as long as . This formalizes the idea that a number is the successor of the number's predecessor. 

Addition between two natural numbers could be defined recursively as follows:

If we use the more common  and  instead of  and , we can see that .

This translates neatly into Python, as shown in the following command snippet:

def add(a: int, b: int) -> int:
if a == 0:
return b else:
return add(a-1, b+1)

We've rearranged common mathematical notation into Python. 

There's no good reason to provide our own functions in Python to do simple addition. We rely on Python's underlying implementation to properly handle arithmetic of various kinds. Our point here is that fundamental scalar arithmetic can be defined recursively, and the definition is very simple to implement.

All of these recursive definitions include at least two cases: the nonrecursive (or base) cases where the value of the function is defined directly, and recursive cases where the value of the function is computed from a recursive evaluation of the function with different values.

In order to be sure the recursion will terminate, it's important to see how the recursive case computes values that approach the defined nonrecursive case. There are often constraints on the argument values that we've omitted from the functions here. The add() function in the preceding command snippet, for example, can include assert a>=0 and b>=0 to establish the constraints on the input values.

Without these constraints, starting with a set to -1 can't be guaranteed to approach the nonrecursive case of a == 0.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset