英文:
How to calculate aggregates over array with mask in Java?
问题
我有一个包含NaN值的基本数据类型数组。如何对它进行聚合计算?比如,org.apache.commons.math3.stat.descriptive.moment.Mean
的输出结果会是NaN。当然,我可以手动编写代码来实现,但也许已经存在一种优雅且高效的解决方案?
英文:
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
得分: 1
如果您使用流API,可以使用filter
函数在计算统计数据时删除NaN
和其他“不规则”值。
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
英文:
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
专注分享java语言的经验与见解,让所有开发者获益!
评论