在Python中,标准的指数运算(
**
)不能用于负数指数!当然,我可以用除法和正数指数来重写公式。但是,我正在检查优化程序的结果,有时幂是负数,有时是正数。这里,一个if语句可以解决问题,但我想知道是否有一种方法和Python库可以允许负指数。
谢谢和问候。你使用的Python版本是哪个?这段代码在Python 2.6、2.7和3.2中都能完美运行:
>>> 3**-3 == 1.0/3**3
True
使用numpy 1.6.1版本:
>>> import numpy as np
>>> arr = np.array([1,2,3,4,5], dtype='float32')
>>> arr**-3 == 1/arr**3
array([ True, True, True, True, True], dtype=bool)
可能是因为我使用的是Python 3.5.1,所以出现了这个错误,与Python 3有关。
for c in np.arange(-5, 5):
print(10 ** c)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-79-7232b8da64c7> in <module>()
1 for c in np.arange(-5, 5):
----> 2 print(10 ** c)
ValueError: Integers to negative integer powers are not allowed.
将其改为浮点数格式,就可以正常工作。
for c in np.arange(-5, 5):
print(10 ** float(c))
1e-05
0.0001
0.001
0.01
0.1
1.0
10.0
100.0
1000.0
10000.0
奇怪的是,在基本的Python 3中它可以工作:
for i in range(-5, 5):
print(10 ** i)
1e-05
0.0001
0.001
0.01
0.1
1
10
100
1000
10000
在Python 2.7.12版本中似乎运行正常:
Python 2.7.12 (default, Oct 11 2016, 05:24:00)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> for c in np.arange(-5, 5):
... print(10 ** c)
...
1e-05
0.0001
0.001
0.01
0.1
1
10
100
1000
10000
>>> import numpy as NP
>>> A = 10*NP.random.rand(12).reshape(4, 3)
>>> A
array([[ 5.7 , 5.05, 7.28],
[ 3.61, 9.67, 6.27],
[ 5.29, 2.8 , 0.58],
[ 5.94, 4.9 , 1.68]])
>>> NP.power(A, -2)
array([[ 0.03, 0.04, 0.02],
[ 0.08, 0.01, 0.03],
[ 0.04, 0.13, 2.98],
[ 0.03, 0.04, 0.35]])
我在Python 2.7中遇到了同样的问题,最终将指数映射为浮点数。虽然不能说这是最佳解决方案。
np.power(10, map(lambda n: float(n), np.arange(-5, 6)))
我以为遇到了相同的问题,但后来发现我没有把数组强制转换成浮点数。一旦我这样做了,它就表现出了我预期的行为。你可能也是做了类似的事情吗?
>>> import numpy as np
>>> arr = np.array([[1,2,3,4],[8,9,10,11]])
>>> arr
array([[ 1, 2, 3, 4],
[ 8, 9, 10, 11]])
>>> arr ** -1
array([[1, 0, 0, 0],
[0, 0, 0, 0]])
>>> arr ** -1.0
array([[ 1. , 0.5 , 0.33333333, 0.25 ],
[ 0.125 , 0.11111111, 0.1 , 0.09090909]])
将会得到
0.25`。 - Tadeck