I have a Numpy array with shape (6,2),
a = array([[1, 2, 3, 3, 2, 1],
[4, 5, 6, 7, 8, 9]])
I want to raise each element of array to two different powers (-6, -8) using np.power(a, [-6,-8])
but this raises ValueError: operands could not be broadcast together with shapes
. How can I do this? Thanks!
Are you trying to get this:
>>> a = np.array([[1, 2, 3, 3, 2, 1], [4, 5, 6, 7, 8, 9]], dtype=float)
>>> np.array([np.power(a, -6), np.power(a, -8)])
array([[[ 1.00000000e+00, 1.56250000e-02, 1.37174211e-03,
1.37174211e-03, 1.56250000e-02, 1.00000000e+00],
[ 2.44140625e-04, 6.40000000e-05, 2.14334705e-05,
8.49985975e-06, 3.81469727e-06, 1.88167642e-06]],
[[ 1.00000000e+00, 3.90625000e-03, 1.52415790e-04,
1.52415790e-04, 3.90625000e-03, 1.00000000e+00],
[ 1.52587891e-05, 2.56000000e-06, 5.95374181e-07,
1.73466526e-07, 5.96046448e-08, 2.32305731e-08]]])
Power doesn't work that way. According to the in-built doc, you can either
np.power(a, 3)
, or np.power(a, b)
, where b
is an array with the same shape as a
, or Raise one array to many powers, as in np.power(a, b)
, where b has "at least" the shape of a, with extra dimensions containing different powers (as I understand it, anyway). So, for your case, the following would also produce the same result:
>>> b = np.array([-6 * np.ones(a.shape), -8 * np.ones(a.shape)]) >>> b array([[[-6., -6., -6., -6., -6., -6.], [-6., -6., -6., -6., -6., -6.]], [[-8., -8., -8., -8., -8., -8.], [-8., -8., -8., -8., -8., -8.]]]) >>> np.power(a, b)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.