0

I have an array of primitives, which can contain Nan values. How do I calculate an aggregate of it? Like, org.apache.commons.math3.stat.descriptive.moment.Mean gives Nan as an output. Of course, I can code this by hand, but maybe an elegant and efficient solution exists already?

1 Answer 1

1

If you use the stream API, you can use the filter function to remove NaN and other "irregular" values when you compute the statistics.

double[] array = {1, Double.NaN, 3};
DoubleSummaryStatistics statistics = Arrays.stream(array).filter(Double::isFinite).summaryStatistics();
double average = statistics.getAverage(); // 2.0
double sum = statistics.getSum(); // 4.0
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot! I'll give it a try.
Btw, how numerically efficient is stream API? I have to call this function many (millions) of times, so it is significant not to slow things down...
Try and see. If it turns out to be a bottle neck later on it's easy to replace with something else

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.