Numpy Heaviside – Compute the Heaviside step function

Featured Image

In this article, we learn how to calculate the Heaviside step function using numpy.heaviside() , a NumPy package function in python. We will get a stronger hold of this topic by implementing a few examples and understanding its syntax.

Also read: Numpy real_if_close – If the input is complex with all imaginary parts close to zero, return real parts

What is numpy.heaviside()?

numpy.heaviside() is a mathematical function of the NumPy package in python. This function is utilized to calculate the Heaviside step function of an input array.

Mathematical representation and rules

We define the mathematical representation and rules to implement numpy.heaviside() below :

  • H(x1,x2) = 0 , if x1 < 0
  • H(x1,x2) = x2 , if x1 = 0
  • H(x1,x2) = 1 , if x1 > 0

Note :
– H is a notation used to represent the Heaviside function other notations like θ, and u are also used.
– The value of x2 is often assumed as 0.5 but 1 or 0 are also sometimes used.

Syntax of numpy.heaviside()

numpy.heaviside(x1, x2, /, out=None, *, where=True)

Parameters

ParameterDescription Required/Optional
x1The input array.Required
x2The input value/array of the function when the value of x1 is 0. If x1.shape != x2.shape, they must be broadcastable to a common shape Required
outThe location where the output is expected to be stored.Optional
whereThe resulting array will be set to ufunc if the condition is set to True otherwise, it will retain its original value.Optional
**kwargsOther keyword parameters.Optional
numpy.heaviside() syntax paramter

Return value

An array consisting of element-wise Heaviside step function of x1.

Examples of using Heaviside

Importing NumPy and displaying the input array.

import numpy as np 
arr=np.array([-1.5,0,2,0.5,10.5,-20])
print("The input array : \n",arr)

Example 1: Basic usage of np.heaviside()

output=np.heaviside(arr,0.5)
print("The output array : \n",output)

arr[0] : -1.5 < 0 thus output[0]= 0
arr[1] : 0 = 0 thus output[1]=0.5
arr[2] : 2 > 0 thus output[2]=1
and so on

The input array :
 [ -1.5   0.    2.    0.5  10.5 -20. ]
The output array :
 [0.  0.5 1.  1.  1.  0. ]

Example 2: Assigning x2 = 1

x2 = np.zeros(4)
print("The output array : \n",np.heaviside([1.5,0.9,-4.5,1], x2))

Output

The output array :
 [1. 1. 0. 1.]

Conclusion

We have implemented and understood the syntax and working of numpy.heaviside() under various parameter values.
Browse more articles at AskPython.

Reference

https://numpy.org/doc/stable/reference/generated/numpy.heaviside.html