Compute the Heaviside step function in Numpy

NumpyServer Side ProgrammingProgramming

To compute the Heaviside step function, use the numpy.heaviside() method in Python Numpy. The 1st parameter is the input array. The 2nd parameter is the value of the function when array element is 0. Returns the output array, element-wise Heaviside step function of x1. This is a scalar if both x1 and x2 are scalars.

The Heaviside step function is defined as −

0 if x1 < 0
heaviside(x1, x2) = x2 if x1 == 0
1 if x1 > 0

where x2 is often taken to be 0.5, but 0 and 1 are also sometimes used.

Steps

At first, import the required library −

import numpy as np

Create an array with float type using the array() method −

arr = np.array([50.8, -3.5, 120.3, 0, 320.1, 450.4, 0])

Display the array −

print("Array...\n", arr)

Get the type of the array −

print("\nOur Array type...\n", arr.dtype)

Get the dimensions of the Array −

print("\nOur Array Dimension...\n",arr.ndim)

Get the shape of the Array −

print("\nOur Array Shape...\n",arr.shape)

To compute the Heaviside step function, use the numpy.heaviside() method in Python Numpy. The 1st parameter is the input array. The 2nd parameter is the value of the function when array element is 0 −

print("\nResult...\n",np.heaviside(arr, 1))

Example

import numpy as np

# Create an array with float type using the array() method
arr = np.array([50.8, -3.5, 120.3, 0, 320.1, 450.4, 0])

# Display the array
print("Array...\n", arr)

# Get the type of the array
print("\nOur Array type...\n", arr.dtype)

# Get the dimensions of the Array
print("\nOur Array Dimension...\n",arr.ndim)

# Get the shape of the Array
print("\nOur Array Shape...\n",arr.shape)

# To compute the Heaviside step function, use the numpy.heaviside() method in Python Numpy
# The 1st parameter is the input array
# The 2nd parameter is the The value of the function when array element is 0
print("\nResult...\n",np.heaviside(arr, 1))

Output

Array...
[ 50.8 -3.5 120.3 0. 320.1 450.4 0. ]

Our Array type...
float64

Our Array Dimension...
1

Our Array Shape...
(7,)

Result...
[1. 0. 1. 1. 1. 1. 1.]
raja
Updated on 08-Feb-2022 10:00:38

Advertisements