Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading