簡體   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