Does a heaviside step function exist?

Probably the simplest method is just

def step(x):
    return 1 * (x > 0)

This works for both single numbers and numpy arrays, returns integers, and is zero for x = 0. The last criteria may be preferable over step(0) => 0.5 in certain circumstances.


If you are using numpy version 1.13.0 or later, you can use numpy.heaviside:

In [61]: x
Out[61]: array([-2. , -1.5, -1. , -0.5,  0. ,  0.5,  1. ,  1.5,  2. ])

In [62]: np.heaviside(x, 0.5)
Out[62]: array([ 0. ,  0. ,  0. ,  0. ,  0.5,  1. ,  1. ,  1. ,  1. ])

With older versions of numpy you can implement it as 0.5 * (numpy.sign(x) + 1)

In [65]: 0.5 * (numpy.sign(x) + 1)
Out[65]: array([ 0. ,  0. ,  0. ,  0. ,  0.5,  1. ,  1. ,  1. ,  1. ])

Tags:

Python

Matlab