简体   繁体   English

如何使用NumPy将数字数组求幂?

[英]How to raise an array of numbers to a power with NumPy?

NumPy has log , log2 , and log10 methods which can perform vectorized log base e / 2 / 10 (respectively). NumPy具有loglog2log10方法,它们可以分别执行矢量化日志e / 2/10。 However, for doing the inverse operation (exponentiation), I only see exp . 但是,对于进行逆运算(求幂),我只看到exp Why is there no exp2 / exp10 / etc? 为什么没有exp2 / exp10等?

I've tried using np.power(10, nums) , but it won't let me raise to a negative power. 我尝试使用np.power(10, nums) ,但是它不会让我提高到负数。 10 ** nums does not work either. 10 ** nums也不起作用。

It should work fine with 10 ** nums provided you use the float dtype. 如果使用float dtype,它应该可以使用10 ** nums正常工作。 Otherwise it will create an integer array: 否则它将创建一个整数数组:

>>> a = numpy.array([-1, 0, 1, 2, 3], dtype=int)
>>> 2 ** a
array([0, 1, 2, 4, 8])
>>> 10 ** a
array([   0,    1,   10,  100, 1000])
>>> a = numpy.array([-1, 0, 1, 2, 3], dtype=float)
>>> 10 ** a
array([  1.00000000e-01,   1.00000000e+00,   1.00000000e+01,
         1.00000000e+02,   1.00000000e+03])

You can also coerce to float by using 10.0 instead of 10 : 您也可以使用10.0而不是10来强制float

>>> a = numpy.array([-1, 0, 1, 2, 3], dtype=int)
>>> 10.0 ** a
array([  1.00000000e-01,   1.00000000e+00,   1.00000000e+01,
         1.00000000e+02,   1.00000000e+03])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM