gpt4 book ai didi

java - 找到最小值的局部最小值

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:03:44 26 4
gpt4 key购买 nike

我有一个 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 中第二高的 double 值。那么,我应该用什么值来初始化 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()) 以避免列表为空时的无限循环。

最佳答案

看起来你只想在调用这段代码后跳出循环

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

如果是这样,那么我建议将您的 while 循环更改为 while(true) 并在 if 声明,或使其成为 while(minDistanceTotal != minDistanceCurrent)

关于java - 找到最小值的局部最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24911581/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com