Why does decimal.Decimal(0)**decimal.Decimal(0)
not return 1 but an error?
import decimal
decimal.Decimal(0)**5 # works and returns Decimal('0') as it should
decimal.Decimal(0)**0 # doesn't not work and should return 1
decimal.Decimal(0)**decimal.Decimal(0) # same
0**0 # works and returns 1
I could use if
statements to bypass the error I get (decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
) but it looks quite dirty to do so.
EDIT : I've always learned in school that 0^0 was 1 but (cf. comments) it is not. So if I want it to be 1 I guess I'll do it manually (in my case that's the desired behaviour), I wasn't aware there was debate as to its value.
CodePudding user response:
Python's decimal
module follows the IBM General Decimal Arithmetic Specification, which says that 0 to the power of 0 raises an Invalid Operation condition and produces NaN. By default, Python raises a decimal.InvalidOperation
exception for Invalid Operation conditions, but you can change the context settings to get the NaN if you want:
In [1]: import decimal
In [2]: decimal.getcontext().traps[decimal.InvalidOperation] = False
In [3]: decimal.Decimal(0)**decimal.Decimal(0)
Out[3]: Decimal('NaN')
As for why the spec defines the operation this way, 0^0=1 is a convention that makes the most sense in discrete contexts. It's not as useful for real numbers. IEEE 754 picked 1.0 for the return value, but IBM made a different choice. Both choices are reasonable.