I'm using Python 2.5.4 and trying to use the decimal module. When I use it in the interpreter, I don't have a problem. For example, this works:
>>> from decimal import *
>>> Decimal('1.2')+ Decimal('2.3')
Decimal("3.5")
But, when I put the following code:
from decimal import *
print Decimal('1.2')+Decimal('2.3')
in a separate file (called decimal.py) and run it as a module, the interpreter complains:
NameError: name 'Decimal' is not defined
I also tried putting this code in a separate file:
import decimal
print decimal.Decimal('1.2')+decimal.Decimal('2.3')
When I run it as a module, the interpreter says:
AttributeError: 'module' object has no attribute 'Decimal'
What's going on?
The as_tuple() and the fma() methodThe as_tuple method is used to represent the decimal as a tuple with three elements. The elements are sign, digits and the exponent value. In the sign field when the number is 0, it means the decimal is positive, when it is 1, it represents the negative number.
Summary. Use the Python decimal module when you want to support fast correctly-rounded decimal floating-point arithmetic. Use the Decimal class from the decimal module to create Decimal object from strings, integers, and tuples. The Decimal numbers have a context that controls the precision and rounding mechanism.
For most use cases, I recommend using decimals. If you initialize them with strings, you prevent subtle bugs and get the increased precision benefits. If you need to eliminate all subtle rounding issues, use the fractions module. Even though floats perform better than decimals, I recommend avoiding floats.
You named your script decimal.py, as the directory the script is in is the first in the path the modules are looked up your script is found and imported. You don't have anything named Decimal in your module which causes this exception to be raised.
To solve this problem simply rename the script, as long as you are just playing around something like foo.py, bar.py, baz.py, spam.py or eggs.py is a good choice for a name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With