[Python-Dev] Example for PEP 343
mcherm at mcherm.com
Tue May 17 23:42:06 CEST 2005
In PEP 343 Guido writes:
> 8. Another use for this feature is the Decimal context. It's left
> as an exercise for the reader. (Mail it to me if you'd like to
> see it here.)
Here are two such examples. Pick your favorite for the PEP.
PS: Writing this helped convince me that allowing the use of generators
instead of classes with the "do_template" decorator is quite nice in
practice, even though it gets confusing (for beginners anyhow) if you
start to think about it too much.
-- Michael Chermside
# ===== SAMPLE #1: increasing precision during a sub-calculation =====
"Performs nested computation with extra digits of precision."
decimal.getcontext().prec += 2
decimal.getcontext().prec -= 2
# == SAMPLE USE of #1 ==
# (Sample taken from the Python Library Reference)
"Return the sine of x as measured in radians."
i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
while s != lasts:
lasts = s
i += 2
fact *= i * (i-1)
num *= x * x
sign *= -1
s += num / fact * sign
# ===== SAMPLE #2: insisting on exact calculations only =====
"Raises exception if nested computation is not exact."
ctx = decimal.getcontext()
was_inexact = ctx.traps[decimal.Inexact]
ctx.traps[decimal.Inexact] = True
ctx.traps[decimal.Inexact] = was_inexact
# == SAMPLE USE of #2 ==
# Lemma 2 ensures us that each fraction will divide evenly
total = decimal.Decimal(0)
for n, d in zip(numerators, denominators):
total += n / d
More information about the Python-Dev