5

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?

6
  • 2
    Why is it wrong? it seems to me like the lowest number in the array. Commented Apr 29, 2012 at 5:04
  • @BinyaminSharet did you scroll down? isnt 7.719277021974478E-73 smaller than that? Commented Apr 29, 2012 at 5:07
  • No no no, the bigger the X in the E-X, the lower the number... this is scientific notation... Commented Apr 29, 2012 at 5:08
  • @BinyaminSharet ooh my bad math :) ok so your answer is right then :) Commented Apr 29, 2012 at 5:10
  • @lonesome Please check my edit and see if it's clearer and asks the right question. Commented Apr 29, 2012 at 5:17

1 Answer 1

7

You can check for zero:

double min = Double.MAX_VALUE;
for (double d : ds) 
{
    min = (d == 0) ? min : Math.min(min, d);
}
Sign up to request clarification or add additional context in comments.

3 Comments

shouldnt it be Double.MIN_VALUE?
Nope. if you start with Double.MIN_VALUE, you'll always get it as a result (Double.MIN_VALUE) regardless of what your array contains, if you start with Double.MAX_VALUE, you'll get the lowest in the array.
I have looked, see my comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.