NumPy数组操作数的负指数

kir*_*off 5 python math numpy scipy

**Python中的标准功率运算()不适用于负功率!当然,我可以用除法和正数来写公式。但是,我正在检查优化例程的结果,有时功率为负,有时为正。这里还是可以使用if语句,但是我想知道是否存在允许负暴露的workarouns和Python库。谢谢并恭祝安康。

dmy*_*tro 6

您正在使用哪个版本的python?在Python 2.6、2.7和3.2中非常适合我:

>>> 3**-3 == 1.0/3**3
True
Run Code Online (Sandbox Code Playgroud)

以及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)
Run Code Online (Sandbox Code Playgroud)


Pau*_*aul 5

这可能是 Python 3 的东西,因为我使用的是 3.5.1,我相信这是您遇到的错误...

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.
Run Code Online (Sandbox Code Playgroud)

只需将其更改为浮点数,它就会起作用。

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
Run Code Online (Sandbox Code Playgroud)

奇怪的是,它适用于基本 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
Run Code Online (Sandbox Code Playgroud)

它似乎适用于 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
Run Code Online (Sandbox Code Playgroud)