找到当地的最小值

时间:2014-07-23 13:18:25

标签: java

我有一个double值列表(点p0和点列表L之间的距离),我正在寻找它们的最小值。然后我正在更改列表(现在包含点p1和点列表L之间的距离)并计算此新的最小值。 我重复此操作,直到新的最小值大于上一步的最小值。

在伪Java代码中:

double minDistanceTotal = Double.MAX_VALUE;
double minDistanceCurrent = ?????;
while (minDistanceCurrent < minDistanceTotal) {
    Point curPoint = ... // take another point p0, p1, p2...
    // compute current minimum distance
    for (Point otherPoint : pointList) {
        double curDistance = distance(curPoint, otherPoint);
        if (curDistance < minDistanceCurrent) {
            minDistanceCurrent = curDistance;
        }
    }
    // compare it to the total minimum distance
    if (minDistanceCurrent < minDistanceTotal) {
        ... // do something
        minDistanceTotal = minDistanceCurrent;
    }
}

我现在的问题是我不确定如何初始化minDistanceCurrent。首先我尝试了Double.MAX_VALUE - 1,但是while - 循环根本没有执行。 检查Java API后,找到Double.MAX_VALUE的实际值0x1.fffffffffffffP+1023。所以我尝试0x1.ffffffffffffeP+1023作为minDistanceCurrent的值,这似乎有效。

但我不确定这是否真的是Java中第二高的双倍值。 那么,我应该用minDistanceCurrent初始化的价值是什么?或者是否有一些不同的方法来获得我想要的错过了?

编辑:在@resueman回答之后,我意识到代码中存在缺陷。检查当前最小值和总最小值只能在计算出新的电流最小值之后而不是之前(因为它处于while循环的条件下)。

使用以下代码修复了问题:

double minDistanceTotal = Double.MAX_VALUE;
double minDistanceCurrent = Double.MAX_VALUE;
while (true) {
    Point curPoint = ... // take another point
    // compute current minimum distance
    for (Point otherPoint : pointList) {
        double curDistance = distance(curPoint, otherPoint);
        if (curDistance < minDistanceCurrent) {
            minDistanceCurrent = curDistance;
        }
    }
    // compare it to the total minimum distance
    if (minDistanceCurrent < minDistanceTotal) {
        ... // do something
        minDistanceTotal = minDistanceCurrent;
    } else {
        break;
    }
}

当列表为空时,替代方法是while(!pointList.isEmpty())以避免无限循环。

2 个答案:

答案 0 :(得分:1)

看起来你只想在调用这段代码之后突破循环

if (minDistanceCurrent < minDistanceTotal) {
    ... // do something
    minDistanceTotal = minDistanceCurrent;
}

如果是这种情况,那么我建议您将while循环更改为while(true)并在if语句中暂停,或者将其设置为while(minDistanceTotal != minDistanceCurrent) {{1}}

答案 1 :(得分:0)

如果我没错,你的循环只执行一次。距离&#39;距离&#39;方法低于MAX_VALUE或溢出double。无论如何,你的上一个&#39; if&#39;将当前和总距离设置为相等,从而让你走出循环。我怀疑这是你真正想要的。

可能你只想在循环开始时制作minDistanceTotal = minDistanceCurrent,并且你可能想要使用BigDecimal而不是double来避免溢出和不准确的计算,但是我不能真正说出来,因为我没有&#39 ; t得到你的算法背后的想法。

汇总:

  1. 请注意如何计算距离(curPoint,otherPoint)&#34;内的距离,尤其要考虑溢出效果。也许使用BigDecimal而不是Double。
  2. 乘坐最后一个if并改变它,无论你真正需要做什么。
  3. 希望它有所帮助。

相关问题