如何在Java中计算带有掩码的数组聚合?

huangapple go评论92阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年4月6日 20:14:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/61059626.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定