Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating power for Decimals in Python

Tags:

python

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
like image 477
Mayank Jain Avatar asked Jul 10 '13 10:07

Mayank Jain


People also ask

How do you calculate power with decimal?

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.


1 Answers

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')
like image 189
mishik Avatar answered Sep 28 '22 20:09

mishik