有效地检测python中的符号变化 [英] Efficiently detect sign-changes in python
问题描述
我想确切地做这个人所做的事情:
I want to do exactly what this guy did:
但是我需要对其进行优化以使其超快运行.简而言之,我想采用一个时间序列,并告诉它每次穿越时都越过零(更改符号).我想记录两次过零之间的时间.由于这是真实数据(32位浮点数),我怀疑我每个人都有一个正好为零的数字,所以这并不重要.我目前有一个计时程序,所以我将对您的成绩进行计时,看看谁赢了.
However I need to optimize it to run super fast. In brief I want to take a time series and tell every time it crosses crosses zero (changes sign). I want to record the time in between zero crossings. Since this is real data (32 bit float) I doubt I'll every have a number which is exactly zero, so that is not important. I currently have a timing program in place so I'll time your results to see who wins.
我的解决方案给出了(微秒):
My solution gives (micro seconds):
open data 8384
sign data 8123
zcd data 415466
如您所见,过零检测器是最慢的部分.这是我的代码.
As you can see the zero-crossing detector is the slow part. Here's my code.
import numpy, datetime
class timer():
def __init__(self):
self.t0 = datetime.datetime.now()
self.t = datetime.datetime.now()
def __call__(self,text='unknown'):
print text,'\t',(datetime.datetime.now()-self.t).microseconds
self.t=datetime.datetime.now()
def zcd(data,t):
sign_array=numpy.sign(data)
t('sign data')
out=[]
current = sign_array[0]
count=0
for i in sign_array[1:]:
if i!=current:
out.append(count)
current=i
count=0
else: count+=1
t('zcd data')
return out
def main():
t = timer()
data = numpy.fromfile('deci.dat',dtype=numpy.float32)
t('open data')
zcd(data,t)
if __name__=='__main__':
main()
推荐答案
有关:
import numpy
a = [1, 2, 1, 1, -3, -4, 7, 8, 9, 10, -2, 1, -3, 5, 6, 7, -10]
zero_crossings = numpy.where(numpy.diff(numpy.sign(a)))[0]
输出:
> zero_crossings
array([ 3, 5, 9, 10, 11, 12, 15])
即,zero_crossings将包含元素之前的索引,该元素发生零交叉.如果要在元素之后,只需将1添加到该数组.
I.e., zero_crossings will contain the indices of elements before which a zero crossing occurs. If you want the elements after, just add 1 to that array.
这篇关于有效地检测python中的符号变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!