Using Double.POSITIVE_INFINITY in Java to find minimum value
Asked Answered
D

2

5

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.

Deluna answered 13/9, 2013 at 20:54 Comment(1)
What happened when you tried it?Armilla
T
7

It is safe to use 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.

Tombouctou answered 13/9, 2013 at 21:10 Comment(0)
B
2

Just set the minimum to the first element of the array (values[0) since you assume that at-least one value exists. If there is only one element, it must be the minimum, and otherwise, it will be updated accordingly.

Bogeyman answered 13/9, 2013 at 20:55 Comment(1)
Obviously that would work, but the real application here is a two-dimensional array of values, any of which may be flagged for skipping. There's no convenient "first element" to use in this case.Deluna

© 2022 - 2024 — McMap. All rights reserved.