Here are some examples of ufunc operations in NumPy:
Example 1: Basic Arithmetic Operations
import numpy as np
# Create two arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
# Addition
result_add = np.add(a, b)
print("Addition:", result_add)
# Subtraction
result_subtract = np.subtract(a, b)
print("Subtraction:", result_subtract)
# Multiplication
result_multiply = np.multiply(a, b)
print("Multiplication:", result_multiply)
# Division
result_divide = np.divide(a, b)
print("Division:", result_divide)
Example 2: Trigonometric Functions
# Create an array of angles in radians
angles = np.array([0, np.pi/2, np.pi])
# Calculate sine and cosine
sine_values = np.sin(angles)
cosine_values = np.cos(angles)
print("Sine values:", sine_values)
print("Cosine values:", cosine_values)
Example 3: Exponential and Logarithmic Functions
# Create an array
x = np.array([1, 2, 3])
# Calculate exponential and natural logarithm
exp_values = np.exp(x)
log_values = np.log(x)
print("Exponential values:", exp_values)
print("Logarithmic values:", log_values)
Example 4: Using Broadcasting
# Create a 1D array and a scalar
array = np.array([1, 2, 3])
scalar = 10
# Add scalar to the array (broadcasting)
result_broadcast = array + scalar
print("Broadcasting result:", result_broadcast)
These examples demonstrate how ufuncs can be used for various mathematical operations on NumPy arrays efficiently.
