Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why decimal.Decimal(0)**decimal.Decimal(0) doesn't return 1

Tags:

python

math

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.

like image 902
FluidMechanics Potential Flows Avatar asked Oct 15 '25 06:10

FluidMechanics Potential Flows


1 Answers

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.

like image 83
user2357112 supports Monica Avatar answered Oct 17 '25 19:10

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!