简体   繁体   English

在Java中使用Double.POSITIVE_INFINITY来查找最小值

[英]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.

相关问题 在for循环中使用Double.POSITIVE_INFINITY(Java) - Using Double.POSITIVE_INFINITY in for loop (Java) Double.POSITIVE_INFINITY的hashCode - hashCode of Double.POSITIVE_INFINITY 有什么方法可以打印java中超过Double.POSITIVE_INFINITY的double的确切值? - is there any ways to print the exact value of a double that exceeds Double.POSITIVE_INFINITY in java? 如何将 Double.POSITIVE_INFINITY 转换为 BigDecimal? - How to convert Double.POSITIVE_INFINITY to BigDecimal? Double.POSITIVE_INFINITY == Float.POSITIVE_INFINITY - Double.POSITIVE_INFINITY == Float.POSITIVE_INFINITY 比较两个具有Double.positive_infinity值的变量是否合法? - is it legal to compare two variables with both Double.positive_infinity values? 为什么将首选大小设置为Double.POSITIVE_INFINITY或Double.MAX_VALUE在JavaFX中不起作用,而在10000中呢? - Why setting the preferred size to Double.POSITIVE_INFINITY or Double.MAX_VALUE does not work in JavaFX while 10000 does? 在 JUnit 5 参数化测试中。 CSV 输入。 有没有办法通过 Double.NaN,Double.POSITIVE_INFINITY? - In JUnit 5 parametrized tests. CSV inputs. Is there a way to pass Double.NaN, Double.POSITIVE_INFINITY? 为什么java在超过Double.Max_Value时返回正无穷大? - why java is returning positive infinity when it exceed Double.Max_Value? 在Double类中为NaN,POSITIVE_INFINITY和其他一些常量设置的值是什么? - What is the value set for NaN, POSITIVE_INFINITY and some other constants in Double class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM