I want to calculate power for Decimal
in Python like:
from decimal import Decimal
Decimal.power(2,2)
Above should return me as Decimal('2)
How can I calculate power for Decimals
?
EDIT: This is what i did
y = Decimal('10')**(x-deci_x+Decimal(str(n))-Decimal('1'))
x,deci_x are of decimal type
but above expression is throwing error as:
decimal.InvalidOperation: x ** (non-integer)
Stacktrace:
Traceback (most recent call last):
File "ha.py", line 28, in ?
first_k_1=first_k(2,n-1,k)
File "ha.py", line 18, in first_k
y = Decimal('10')**(x-deci_x+Decimal(str(n))-Decimal('1'))
File "/usr/lib64/python2.4/decimal.py", line 1709, in __pow__
return context._raise_error(InvalidOperation, 'x ** (non-integer)')
File "/usr/lib64/python2.4/decimal.py", line 2267, in _raise_error
raise error, explanation
When taking the power of a decimal, first count the number of decimal places in the base number, as when multiplying decimals (see Decimal Multiplication. Next, multiply that number by the exponent. This will be the total number of decimal places in the answer.
You can calculate power using **
:
2**3 # yields 8
a = Decimal(2)
a**2 # yields Decimal(4)
Following your update, seems okay for me:
>>> x = Decimal(2)
>>> deci_x = Decimal(1)
>>> n=4
>>> y = Decimal('10')**(x-deci_x+Decimal(str(n))-Decimal('1'))
>>> y
Decimal('10000')
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