[英]Why would this Python function break in a loop?
從這個問題
我正在使用Python解決方案,如果我自己運行它,它的效果很好。
但我有這些'曲線'的字典:
上證所{}
{'00': [4.998436383771836,
0.0160165895672664,
0.004512422186993107,
0.0013171501024742112,
0.000788783358847752,
0.0005498425886621068],
'67':[0.13598930783101504,
0.04717783658889547,
0.027547125931827038,
0.021440839841617088,
0.016775671441391703,
0.013185864754748117,
0.010318462898609907],
等等...
如果我運行它,它完美地工作:
curve = sse['67']
nPoints = len(curve)
allCoord = np.vstack((range(nPoints), curve)).T
np.array([range(nPoints), curve])
firstPoint = allCoord[0]
lineVec = allCoord[-1] - allCoord[0]
lineVecNorm = lineVec / np.sqrt(np.sum(lineVec**2))
vecFromFirst = allCoord - firstPoint
scalarProduct = np.sum(vecFromFirst * np.matlib.repmat(lineVecNorm, nPoints, 1), axis=1)
vecFromFirstParallel = np.outer(scalarProduct, lineVecNorm)
vecToLine = vecFromFirst - vecFromFirstParallel
distToLine = np.sqrt(np.sum(vecToLine ** 2, axis=1))
idxOfBestPoint = np.argmax(distToLine)
print(idxOfBestPoint)
但是當我嘗試使它成為循環函數時,我會得到奇怪的值,這些值在單獨運行時不匹配:
for k in sse:
curve = sse[str(k)]
nPoints = len(curve)
allCoord = np.vstack((range(nPoints), curve)).T
np.array([range(nPoints), curve])
firstPoint = allCoord[0]
lineVeceVeceVec = allCoord[-1] - allCoord[0]
lineVecNorm = lineVec / np.sqrt(np.sum(lineVec**2))
vecFromFirst = allCoord - firstPoint
scalarProduct = np.sum(vecFromFirst * np.matlib.repmat(lineVecNorm, nPoints, 1), axis=1)
vecFromFirstParallel = np.outer(scalarProduct, lineVecNorm)
vecToLine = vecFromFirst - vecFromFirstParallel
distToLine = np.sqrt(np.sum(vecToLine ** 2, axis=1))
idxOfBestPoint = np.argmax(distToLine)
print(idxOfBestPoint, k)
它會吐出這樣的東西:
7 57
98 11
6 45
4 50
98 91
98 00
1 62
98 79
7 48
98 12
98 38
98 23
5 37
98 56
98 67
5 25
7 46
98 22
98 49
2 47
98 41
98 78
98 35
98 68
98 14
98 24
1 0
98 42
我不知道是否有一些變量沒有重置或者什么會導致它失敗,添加一個簡單的循環?
要清楚它確實運行了,但是計算結果是將'98'作為肘部放在循環上,但是當它單獨運行時,對於'67'曲線列表將是7,而不是98。
你有一個拼寫錯誤: lineVeceVeceVec = allCoord[-1] - allCoord[0]
。 它應該是lineVec = allCoord[-1] - allCoord[0]
。 所以你吐出的是最后一次將lineVec
分配給結果,而最后一個值可能來自你運行非循環版本時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.