Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 945
donnyton Avatar asked Feb 16 '23 07:02

donnyton


2 Answers

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.

like image 147
rolfl Avatar answered Feb 17 '23 21:02

rolfl


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.

like image 20
Tommy Avatar answered Feb 17 '23 20:02

Tommy