Functional Python Programming

(Wang) #1
Chapter 13

Here's a continuation of the preceding example of the itertools.starmap() function:





p = (3, 8, 29, 44)
pi = sum(starmap(truediv, zip(p, d)))





We've zipped together two sequences of four values. We used the starmap()
function with the operator.truediv() function, which is the / operator.
This will compute a sequence of fractions that we sum. The sum is really an
approximation of π


Here's a simpler version that uses the map(f, x, y) function instead of the
starmap(f, zip(x,y)) function:





pi = sum(map(truediv, p, d))
pi
3.1415925925925925





In this example, we effectively converted a base 60 fractional value to base 10. The
sequence of values in the d variable are the appropriate denominators. A technique
similar to the one explained earlier in this section can be used to convert other bases.


Some approximations involve potentially infinite sums (or products). These can
be evaluated using similar techniques explained previously in this section. We can
leverage the count() function in the itertools module to generate an arbitrary
number of terms in an approximation. We can then use the takewhile() function to
only use values that contribute a useful level of precision to the answer.


Here's an example of a potentially infinite sequence:





num= map(fact, count())
den= map(semifact, (2n+1 for n in count()))
terms= takewhile(lambda t: t > 1E-10, map(truediv, num, den))
2
sum(terms)
3.1415926533011587





The num variable is a potentially infinite sequence of numerators, based on a factorial
function. The den variable is a potentially infinite sequence of denominators, based
on the semifactorial (sometimes called the double factorial) function.


To create terms, we used the map() function to apply the operators.truediv()
function, the / operator, to each pair of values. We wrapped this in a takewhile()
function so that we only take values while the fraction is greater than some relatively
small value; in this case, 1 10× −^10.

Free download pdf