Elaborate Decimal context example, thanks to Michael Chermside.
This commit is contained in:
parent
2e09a4c99d
commit
b99aa09cf2
30
pep-0343.txt
30
pep-0343.txt
|
@ -388,9 +388,33 @@ Examples
|
|||
by default all signals are blocked. The implementation is left
|
||||
as an exercise to the reader.
|
||||
|
||||
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.)
|
||||
8. Another use for this feature is the Decimal context. Here's a
|
||||
simple example, after one posted by Michael Chermside:
|
||||
|
||||
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
|
||||
|
||||
|
|
Loading…
Reference in New Issue