[英]Using Double.POSITIVE_INFINITY in Java to find minimum value
Simple question: will the following code work for finding the minimum value in an array of doubles (assume at least one value exists): 简单的问题:以下代码是否可用于查找双精度数组中的最小值(假设至少存在一个值):
double[] values = ...
double currentMin = Double.POSITIVE_INFINITY;
for(int i = 0; i < values.length; i++) {
if(values[i] < currentMin) {
currentMin = values[i];
}
}
return currentMin;
The crux of the question is whether POSITIVE_INFINITY will behave as expected when compared to other (real) double values, as well as potential infinities themselves. 问题的关键在于POSITIVE_INFINITY与其他(实际)双重值以及潜在的无限性本身相比是否会表现得如预期。
It is safe to use Double.POSITIVE_INFINITY. 使用Double.POSITIVE_INFINITY是安全的。 From the specification
从规范
All values other than NaN are ordered, with negative infinity less than all finite values, and positive infinity greater than all finite values.
NaN以外的所有值都是有序的,负无穷大小于所有有限值,正无穷大大于所有有限值。
Just set the minimum to the first element of the array (values[0) since you assume that at-least one value exists. 只需将最小值设置为数组的第一个元素(值[0],因为您假设至少存在一个值。 If there is only one element, it must be the minimum, and otherwise, it will be updated accordingly.
如果只有一个元素,则必须是最小元素,否则,它将相应更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.