[Python] NumPy Universal Functions (ufunc): Batch Calculation for All Array Elements

One of NumPy’s greatest features is “Universal Functions” (abbreviated as ufunc), which allow you to apply a function to all elements of an array at once.

Compared to calculating each item one by one using standard Python for loops, ufuncs process data overwhelmingly faster and make the code much simpler.

目次

Executable Sample Code

The following code is an example of applying trigonometric functions (sin), square roots (sqrt), and exponential functions (exp) to an entire array.

import numpy as np

def ufunc_demo():
    print("=== 1. Calculation of Trigonometric Functions (User Example) ===")
    # Create an array from 0 to 9
    x = np.arange(0, 10)
    print(f"Original x: {x}")
    
    # Calculate sin for all elements of the array
    # While standard Python's math.sin(x) would raise an error, np.sin(x) works
    y = np.sin(x)
    print(f"np.sin(x):  {y}")

    print("\n=== 2. Other Mathematical Functions ===")
    # Square Root
    x2 = np.array([1, 4, 9, 16])
    print(f"Original x2: {x2}")
    print(f"np.sqrt(x2): {np.sqrt(x2)}") # [1. 2. 3. 4.]

    # Exponential function (e^x)
    print(f"np.exp(x2):  {np.exp(x2)}")

    print("\n=== 3. Operations Between Arrays (Arithmetic ufuncs) ===")
    a = np.array([10, 20, 30])
    b = np.array([1, 2, 3])
    
    # Standard operators are processed as ufuncs (e.g., np.add) internally
    print(f"a + b: {a + b}")       # Same as np.add(a, b)
    print(f"a * b: {a * b}")       # Same as np.multiply(a, b)
    print(f"a ** 2: {a ** 2}")     # Same as np.power(a, 2)

if __name__ == "__main__":
    ufunc_demo()

Explanation: Benefits of Universal Functions

1. Element-wise Calculation

Simply by writing np.sin(x), the sin calculation is performed for all of x[0], x[1], etc. This is called “element-wise calculation.”

2. High-Speed Processing (Vectorization)

While Python’s for loops are slow in processing speed, NumPy’s universal functions use loops optimized at the C language level. Therefore, when handling large amounts of data, they can achieve speeds several times to hundreds of times faster.

List of Major Universal Functions

Function NameDescriptionSubstitute Operator
np.add(x, y)Additionx + y
np.subtract(x, y)Subtractionx - y
np.multiply(x, y)Multiplicationx * y
np.divide(x, y)Divisionx / y
np.power(x, y)Exponentiationx ** y
np.sqrt(x)Square RootNone
np.sin(x), np.cos(x)Trigonometric FunctionsNone
np.log(x)Natural LogarithmNone
np.abs(x)Absolute ValueNone
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次