为什么 decimal.Decimal(0)**decimal.Decimal(0) 不 return 1
Why decimal.Decimal(0)**decimal.Decimal(0) doesn't return 1
为什么 decimal.Decimal(0)**decimal.Decimal(0)
不是 return 1 而是一个错误?
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
我可以使用 if
语句来绕过我得到的错误 (decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
),但这样做看起来很脏。
编辑:我一直在学校学习 0^0 是 1,但(参见评论)它不是。因此,如果我希望它为 1,我想我会手动执行(在我的情况下这是所需的行为),我不知道关于它的值存在争议。
Python 的 decimal
模块遵循 IBM General Decimal Arithmetic Specification, which says 0 的 0 次方引发无效操作条件并生成 NaN。默认情况下,Python 会针对无效操作条件引发 decimal.InvalidOperation
异常,但您可以根据需要更改上下文设置以获取 NaN:
In [1]: import decimal
In [2]: decimal.getcontext().traps[decimal.InvalidOperation] = False
In [3]: decimal.Decimal(0)**decimal.Decimal(0)
Out[3]: Decimal('NaN')
至于为什么规范以这种方式定义操作,0^0=1 是在离散上下文中最有意义的约定。它对实数没那么有用。 IEEE 754 为 return 值选择了 1.0,但 IBM 做出了不同的选择。两种选择都是合理的。
为什么 decimal.Decimal(0)**decimal.Decimal(0)
不是 return 1 而是一个错误?
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
我可以使用 if
语句来绕过我得到的错误 (decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]
),但这样做看起来很脏。
编辑:我一直在学校学习 0^0 是 1,但(参见评论)它不是。因此,如果我希望它为 1,我想我会手动执行(在我的情况下这是所需的行为),我不知道关于它的值存在争议。
Python 的 decimal
模块遵循 IBM General Decimal Arithmetic Specification, which says 0 的 0 次方引发无效操作条件并生成 NaN。默认情况下,Python 会针对无效操作条件引发 decimal.InvalidOperation
异常,但您可以根据需要更改上下文设置以获取 NaN:
In [1]: import decimal
In [2]: decimal.getcontext().traps[decimal.InvalidOperation] = False
In [3]: decimal.Decimal(0)**decimal.Decimal(0)
Out[3]: Decimal('NaN')
至于为什么规范以这种方式定义操作,0^0=1 是在离散上下文中最有意义的约定。它对实数没那么有用。 IEEE 754 为 return 值选择了 1.0,但 IBM 做出了不同的选择。两种选择都是合理的。