代码之家  ›  专栏  ›  技术社区  ›  user3486773

为什么这个python函数会中断循环?

  •  0
  • user3486773  · 技术社区  · 6 年前

    从这个问题

    Finding the best trade-off point on a curve

    我正在使用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
    

    我不知道是否有某个变量没有重置,或者添加一个简单的循环会导致它失败?

    要清楚的是,它确实在运行,但是Calc将'98'作为循环的肘部,但是当单独运行时,它将是'67'曲线列表的7,而不是98。

    1 回复  |  直到 6 年前
        1
  •  0
  •   rayryeng    6 年前

    你的拼写错误: lineVeceVeceVec = allCoord[-1] - allCoord[0] 是的。应该是 lineVec = allCoord[-1] - allCoord[0] 是的。所以你说的是最后一次 lineVec 已分配给结果,最后一个值可能来自运行非循环版本时的值。