Does a heaviside step function exist?


Question

Is there a heaviside function in Python similar to that of MATLAB's heaviside?

I am struggling to find one.

1
26
2/27/2013 8:04:51 PM

Accepted Answer

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. ])
46
2/24/2018 10:26:04 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon