Elaborate Decimal context example, thanks to Michael Chermside.

This commit is contained in:
Guido van Rossum 2005-05-17 22:15:50 +00:00
parent 2e09a4c99d
commit b99aa09cf2
1 changed files with 27 additions and 3 deletions

View File

@ -388,9 +388,33 @@ Examples
by default all signals are blocked. The implementation is left by default all signals are blocked. The implementation is left
as an exercise to the reader. as an exercise to the reader.
8. Another use for this feature is the Decimal context. It's left 8. Another use for this feature is the Decimal context. Here's a
as an exercise for the reader. (Mail it to me if you'd like to simple example, after one posted by Michael Chermside:
see it here.)
import decimal
@do_template
def with_extra_precision(places=2):
c = decimal.getcontext()
saved_prec = c.prec
c.prec += places
yield None
c.prec = saved_prec
Sample usage (adapted from the Python Library Reference):
def sin(x):
"Return the sine of x as measured in radians."
do with_extra_precision():
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
return +s
References References