📜  numpy ufunc |通用功能(1)

📅  最后修改于: 2023-12-03 15:33:14.270000             🧑  作者: Mango

NumPy ufunc - Universal Functions

NumPy ufunc (universal functions) are a set of functions provided by the NumPy package, which allows for element-wise operations on arrays of different sizes and shapes. These operations are vectorized, meaning that they can be applied to the entire array, without the need for a loop or cumbersome indexing.

Advantages of ufuncs
  • Vectorization of operations leads to faster execution times.
  • Code is simpler and easier to read.
  • Allows for element-wise operations between arrays of different sizes and shapes.
Examples of ufuncs
Addition of two arrays
import numpy as np

x = np.array([1, 2, 3])
y = np.array([4, 5, 6])

z = x + y

print(z)

Output:

array([5, 7, 9])
Trigonometric Functions
import numpy as np

x = np.array([0, np.pi/4, np.pi/2])

print(np.sin(x))
print(np.cos(x))
print(np.tan(x))

Output:

array([ 0.        ,  0.70710678,  1.        ])
array([ 1.        ,  0.70710678,  0.        ])
array([ 0.        ,  1.        ,  inf])
Exponential and logarithmic functions
import numpy as np

x = np.array([1, 2, 3])

print(np.exp(x))
print(np.log(x))
print(np.log10(x))

Output:

array([  2.71828183,   7.3890561 ,  20.08553692])
array([ 0.        ,  0.69314718,  1.09861229])
array([ 0.        ,  0.30103   ,  0.47712125])
Conclusion

By using ufuncs, we can write simple and concise code that performs fast vectorized operations on arrays of different sizes and shapes. This greatly enhances the efficiency and readability of our code when working with numerical computations.