Mayank Jain
Mayank Jain

Reputation: 2564

Calculating power for Decimals in 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

Upvotes: 9

Views: 23956

Answers (4)

joente
joente

Reputation: 856

You can just use the power operator ** with Decimal...

print(Decimal(2)**Decimal(2)) # 4

Edit, followup to your question

You don't need to parse stings to Decimal()...

from decimal import Decimal
x, deci_x, n = Decimal(2), Decimal(3), 4
y = Decimal(10)**(x-deci_x+Decimal(n)-Decimal(1))
print(y) # 100

Upvotes: 4

Kevin
Kevin

Reputation: 76194

Python 2.4.6 does not support non-integer powers for Decimals. From the __pow__ method in decimal.py:

def __pow__(self, n, modulo = None, context=None):
    #[snip]
    if not n._isinteger():
        return context._raise_error(InvalidOperation, 'x ** (non-integer)')

if x-deci_x+Decimal(str(n))-Decimal('1') is always an integer, convert it into the integer type before using it as an exponent. If you need the exponent to be a non-integer, consider upgrading to a more recent version of Python.

Upvotes: 0

danodonovan
danodonovan

Reputation: 20353

In Python >= 3.4 as Decimal has a power function.

>>> decimal.power(Decimal('2'), Decimal('2.5'))

Or simply using the math module;

from math import pow
pow(2, 2)

using decimals

>>> pow(Decimal('2'), Decimal('2'))

and non-integer decimals will also work

>>> pow(Decimal('2'), Decimal('2.5'))

Upvotes: 1

mishik
mishik

Reputation: 10003

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')

Upvotes: 12

Related Questions