Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how do you use decimal module in a script rather than the interpreter?

Tags:

python

decimal

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?

like image 928
jack Avatar asked Jun 26 '10 17:06

jack


People also ask

How do you use the decimal function in Python?

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.

What does decimal decimal do in Python?

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.

Should I use float or decimal Python?

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.


1 Answers

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.

like image 154
DasIch Avatar answered Sep 21 '22 15:09

DasIch