繁体   English   中英

是否存在重载步骤功能?

[英]Does a heaviside step function exist?

是否有在Python功能类似于MATLAB的的heaviside

我很难找到一个。

如果您使用的是numpy版本1.13.0或更高版本,则可以使用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. ])

对于numpy的旧版本,您可以将其实现为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. ])

可能最简单的方法就是

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

这适用于单个数字和numpy数组,返回整数,并且对于x = 0则为零。在某些情况下,最后一个条件可能优于step(0) => 0.5

这是sympy的一部分,你可以用pip install sympy

来自文档:

class sympy.functions.special.delta_functions.Heaviside


Heaviside Piecewise function. Heaviside function has the following properties: 

1) diff(Heaviside(x),x) = DiracDelta(x)    ( 0, if x<0 )
2) Heaviside(x) = < [*] 1/2 if x==0        ( 1, if x>0 )

你会像这样使用它:

In [1]: from sympy.functions.special.delta_functions import Heaviside

In [2]: Heaviside(1)
Out[2]: 1

In [3]: Heaviside(0)
Out[3]: 1/2

In [4]: Heaviside(-1)
Out[4]: 0

你也可以写自己的:

heaviside = lambda x: 0.5 if x == 0 else 0 if x < 0 else 1

如果您需要符号变量,则可能无法满足您的需求。

我不确定它是否开箱即用,但你总能写一个:

def heaviside(x):
    if x == 0:
        return 0.5

    return 0 if x < 0 else 1

从numpy 1.13开始,它是numpy.heaviside

不确定是否有最好的方法来完成任务...但这里是我破解的功能。

def u(t):
    unit_step = numpy.arange(t.shape[0])
    lcv = numpy.arange(t.shape[0])
        for place in lcv:
            if t[place] == 0:
               unit_step[place] = .5
            elif t[place] > 0:
               unit_step[place] = 1
            elif t[place] < 0:
    unit_step[place] = 0
    return unit_step

使用Pylab和NumPy进行Ipython绘图

def heaviside(xx):
    return numpy.where(xx <= 0, 0.0, 1.0) + numpy.where(xx == 0.0, 0.5, 0.0)

或者,如果numpy.where太慢:

def heaviside(xx):
    yy = numpy.ones_like(xx)
    yy[xx < 0.0] = 0.0
    yy[xx == 0.0] = 0.5
    return yy

以下时间是numpy 1.8.2; 在numpy 1.9.0中进行了一些优化,所以请自己尝试一下:

>>> import timeit
>>> import numpy
>>> array = numpy.arange(10) - 5
>>> def one():
...  return numpy.where(array <= 0, 0.0, 1.0) + numpy.where(array == 0.0, 0.5, 0.0)
... 
>>> def two():
...  yy = numpy.ones_like(array)
...  yy[array < 0] = 0.0
...  yy[array == 0] = 0.5
...  return yy
... 
>>> timeit.timeit(one, number=100000)
3.026144027709961
>>> timeit.timeit(two, number=100000)
1.5265140533447266
>>> numpy.__version__
'1.8.2'

在另一台机器上,有一个不同的numpy:

>>> timeit.timeit(one, number=100000)
0.5119631290435791
>>> timeit.timeit(two, number=100000)
0.5458788871765137
>>> numpy.__version__
'1.11.1'
>>> def three():
...  return 0.5*(numpy.sign(array) + 1)
... 
>>> timeit.timeit(three, number=100000)
0.313539981842041

简易方案:

import numpy as np
amplitudes = np.array([1*(x >= 0) for x in range(-5,6)])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM