Python numpy. power of function instructions
- 2021-09-24 22:54:04
- OfStack
The power (x, y) function calculates the y power of x.
Example:
x and y are single digits:
import numpy as np
print(np.power(2, 3))
8
Analysis: 2 to the third power.
x is a list and y is a single number:
print(np.power([2,3,4], 3))
[ 8 27 64]
Analysis: Find the third power of 2, 3 and 4 respectively.
x is a single number and y is a list:
print(np.power(2, [2,3,4]))
[ 4 8 16]
Analysis: Find the 2nd, 3rd and 4th power of 2 respectively.
x and y are lists:
print(np.power([2,3], [3,4]))
[ 8 81]
Analysis: Find the 3rd power of 2 and the 4th power of 3 respectively.
Add: There are details about how to use the power () function in python3. X. X
This function is commonly used in finding Euclidean distance, and it will be used more in handwriting machine learning
Function explanation:
--power (A, B): Find the B power of A, which is mathematically equivalent to A ^ B
Where A and B can be either numbers (scalars) or lists (vectors)
There are three situations:
1. When A and B are both numbers (scalars), it is to find the power of B of A
In [83]: a , b = 3 ,4
In [84]: np.power(a,b)
Out[84]: 81
2. When A is a list (vector) and B is a number (scalar), it is divided into two sub-cases:
--power (A, B): all elements in the A list (vector), find the power of B;
--power (B, A): Generates a list of length len (A) with elements to the power of B ^ A. Look at the example concretely
In [10]: A, B = [1,2,3],3
# List A Adj. B Power: [1^3, 2^3, 3^3]
In [11]: np.power(A,B)
Out[11]: array([ 1, 8, 27])
# Return len(A) A list of lengths in which elements [3^1, 3^2, 3^3]
In [12]: np.power(B,A)
Out[12]: array([ 3, 9, 27])
3. AB must be len (A) = len (B) when all AB are lists (vectors)
In [13]: A , B = [1,2,3],[4,5,6]
In [14]: np.power(A,B)
Out[14]: array([ 1, 32, 729])
# If A And B The length of is not 1 Sample, will report an error
In [15]: A , B = [1,2,3],[4,5,6,7]
In [16]: np.power(A,B)
ValueError: operands could not be broadcast together with shapes (3,) (4,)