假设Python中有两个列表:
a = [1, 2, 3, 4, 5, 6] # y values of a line
b = [7, 6, 4, 4, 8, 4] # x values are index location of the list
// result = [F, F, F, T, F, T]现在,如果您可以想象这些点代表2条线,a和b。线a只是线性上升(尽管这是任意的),而b行向下下降,首先接触where x=4,而不是越过x=6。
我想做的是,有一个简单的和毕达通的解决方案,以检测什么时候线接触或交叉。我想知道numpy或其他库是否已经能做到这一点。
编辑:我写了这个装置,我认为它的工作距离检测交叉。aa <= bb;aa >= bb也应该让它检测到触点。
# check if lines crossed in past X bars
def cross(a, b, bars=3):
aa = np.array(a[-bars:])
bb = np.array(b[-bars:])
if len(np.unique(aa < bb)) == len(np.unique(aa > bb)) == 1:
return False
return True发布于 2015-11-15 11:26:05
首先,把这两条线区别开来。
difference=a-b如果差异的符号从一项更改到下一项,则会有一个交集(在触摸时为空)。你可以这样做:
cross=(np.sign(difference*np.roll(difference,1))<1)[1:][1:]是抛弃第一点而不是相关的。如果前面有一个交叉口,则为True。
完整的例子:
import numpy as np
import matplotlib.pyplot as plt
a=np.random.randint(0,20,20)
b=np.random.randint(0,20,20)
plt.close()
plt.plot(a,'*-')
plt.plot(b,'*-')
difference=a-b
cross=(np.sign(difference*np.roll(difference,1))<1)[1:]
plt.plot(np.arange(.5,19),10* cross, 'd')每一次分段交叉时都有一颗红色的钻石。在这种方法中,触点被认为是双重接触。

发布于 2015-11-15 08:28:41
如果a和b在同一索引下的值相同,那么两条线就会接触,如果a的前一个值高于b的前一个值,而a的当前值下降到b的当前值,那么两条线就会交叉。使用zip同时迭代a和b,并使用变量previous存储以前的信息。
a = [1, 2, 3, 4, 5, 6] # y values of a line
b = [7, 6, 4, 4, 8, 4] # x values are index location of the list
previous = 0
result = []
for x, y in zip(a,b):
if x == y: result.append(True) #touch
else:
comapre_result = 1 if x > y else -1
if comapre_result + previous == 0:#cross-over
result.append(True)
else:
result.append(False)
previous = comapre_result
print resulthttps://stackoverflow.com/questions/33717492
复制相似问题