lonesome
lonesome

Reputation: 2552

finding min but zero

How can I find the smallest positive (non-zero) number in an array of doubles? For example, if the array contains 0.04, 0.0001, and 0.0, I want to return 0.0001.

The below function is good, but it will return zero as the min, which is not my interest.

static double[] absOfSub = new double[100];
...

private static double compare(double[] ds) {
  double min = absOfSub[0];

  for (double d : ds) {
    min = Math.min(min, d);
  }
  return min;
}

How can I make it ignore zeroes?

Upvotes: 5

Views: 3079

Answers (1)

MByD
MByD

Reputation: 137282

You can check for zero:

double min = Double.MAX_VALUE;
for (double d : ds) 
{
    min = (d == 0) ? min : Math.min(min, d);
}

Upvotes: 7

Related Questions