While I agree with many of the other comments here I figured I’d throw a bone.
The decimal
module is a utility for doing arithmetic on numbers of arbitrary precision. This is used in some scientific contexts to do calculations on things that suffer from round-off errors. The classical example would be calculting the 9999th digit of pi. You just can’t do that with floats.
The decimal library uses the concept of a “context” to decide how much precision you really want. Since the more precision you want the slower the calculations will run. The decimal.getcontext()
part returns the default context. But through a crazy “gotcha” (that I’ve actually fallen prey to) this is actually just a pointer. So if you were to change the context with a decimal.setcontext('foo')
you would actually change a
as well. Handily the module has a .copy()
method.
The original programmer probably did this to save a copy of the context for later use. Perhaps s/he wanted to perform a part of the computation at a lower precision to save time and then wanted to perform the difficult part at a higher precision.
Although in python > 2.5 this is best done with a context manager like ‘with’
from decimal import localcontext
with localcontext() as ctx:
ctx.prec -= 5 # Perform a low precision calculation
s = calculate_something()
s = +s # Round the final result back to the default precision
But without the rest of the relevant code my guess is no better than yours.
While I have worked with the decimal module before all of this is easily found in the python docs here. Try to go there and poke around first for questions like this … if you can figure it out yourself you’ll remember it longer. And you’ll get that warm feeling in your head that the rest of us feel when we answer questions.
3
solved what is the ‘decimal.getcontext().copy()’ mean [closed]