Functional Python Programming

(Wang) #1

Optimizations and Improvements


The use of Fraction value here—while possible—doesn't seem to be helpful because
there will be an irrational value computed. However, when we look at the complete
gamma function given here, we'll see that Fraction values are potentially helpful. In
this function, they're merely incidental.


Here's an implementation of the previously explained series expansion:


def gamma(s, z):


def terms(s, z):


for k in range(100):


t2= Fraction(z**(s+k))/(s+k)


term= Fraction((-1)*k,fact(k))t2


yield term


warnings.warn("More than 100 terms")


def take_until(function, iterable):


for v in iterable:


if function(v): return


yield v


ε= 1E-8


return sum(take_until(lambda t:abs(t) < ε, terms(s, z)))


We defined a term() function that will yield a series of terms. We used a for
statement with an upper limit to generate only 100 terms. We could have used the
itertools.count() function to generate an infinite sequence of terms. It seems
slightly simpler to use a loop with an upper bound.


We computed the irrational zsk+ value and created a Fraction value from this value
by itself. If the value for z is also a Fraction value and not a float value then, the
value for t2 will be a Fraction value. The value for term() function will then be a
product of two Fraction objects.


We defined a take_until() function that takes values from an iterable, until a given
function is true. Once the function becomes true, no more values are consumed from
the iterable. We also defined a small threshold value, ε, of 10 −^8. We'll take values
from the term() function until the values are less than ε. The sum of these values is
an approximation to the partial gamma function.

Free download pdf