Aug*_*sta 0 python math exponentiation negative-number python-2.7
Python似乎无法将数字的正确值返回到零的幂.当我给它一个文字方程时,它可以正常工作,但它总是返回正1,对于比原始数字更复杂的零到零.
以下是一些测试:
>>> -40 ** 0 # this is the correct result
-1
>>> (0 - 40) ** 0 # you'd expect this to give the same thing, but...
1
>>> a = -40 # let's try something else...
>>> a ** 0
1
>>> int(-40) ** 0 # this oughtn't to change anything, yet...
1
>>> -66.6 ** 0 # raw floats are fine.
-1.0
>>> (0 - 66.6) ** 0.0 # ...until you try and do something with them.
1.0
Run Code Online (Sandbox Code Playgroud)
更新:也pow()给出了这个结果,所以第一个结果可能是例外......
>>> pow(-60, 0)
1
Run Code Online (Sandbox Code Playgroud)
签名整数会有问题吗?我需要这个用于值为1,-1或0的三重开关,具体取决于输入是正值还是负值,或者为零.我可以通过以下方式完成同样的事情:
if val > 0: switch = 1
elif val < 0: switch = -1
else: switch = 0
Run Code Online (Sandbox Code Playgroud)
...然后将变量开关用于我的目的.
但这不会回答我关于Python如何处理零功率的问题.
(我也会接受-40 ** 0只是偶然返回-1 (现象),但我怀疑是这种情况......)
Python是正确的并且正在做你期望它做的事情.这是一个操作顺序问题.第零次幂的任何数字(负数或正数)等于1.但请记住,乘法在运算顺序减去之前.所以更详细地说,python看到的是:第一种情况:
-40 ** 0 = -(40 ** 0) = -(1) = -1
Run Code Online (Sandbox Code Playgroud)
第二个案例:
(0 - 40) ** 0 = (-40) ** 0 = 1
Run Code Online (Sandbox Code Playgroud)
在第五种情况下它也与括号有关
int(-40) ** 0 = (-40) ** 0 = 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
88 次 |
| 最近记录: |