如何从一组数字计算平均值,中位数,模式和范围

编程入门 行业动态 更新时间:2024-10-28 13:13:27
本文介绍了如何从一组数字计算平均值,中位数,模式和范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否有任何函数(作为数学库的一部分)将计算意味着,中位数,模式和范围来自一组数字。

Are there any functions (as part of a math library) which will calculate mean, median, mode and range from a set of numbers.

推荐答案

是的,似乎确实有第3个库(Java Math中没有)。其中两个是:

Yes, there does seem to be 3rd libraries (none in Java Math). Two that have come up are:

http:// opsresearch。 com / app /

www.iro.umontreal.ca/~simardr/ssj/indexe.html

但实际上并非如此难以编写自己的方法来计算平均值,中位数,模式和范围。

but, it is actually not that difficult to write your own methods to calculate mean, median, mode and range.

MEAN

public static double mean(double[] m) { double sum = 0; for (int i = 0; i < m.length; i++) { sum += m[i]; } return sum / m.length; }

MEDIAN

// the array double[] m MUST BE SORTED public static double median(double[] m) { int middle = m.length/2; if (m.length%2 == 1) { return m[middle]; } else { return (m[middle-1] + m[middle]) / 2.0; } }

模式

public static int mode(int a[]) { int maxValue, maxCount; for (int i = 0; i < a.length; ++i) { int count = 0; for (int j = 0; j < a.length; ++j) { if (a[j] == a[i]) ++count; } if (count > maxCount) { maxCount = count; maxValue = a[i]; } } return maxValue; }

UPDATE

正如Neelesh Salpe所指出的,上述内容并不适合多模式收藏。我们可以很容易地解决这个问题:

As has been pointed out by Neelesh Salpe, the above does not cater for multi-modal collections. We can fix this quite easily:

public static List<Integer> mode(final int[] numbers) { final List<Integer> modes = new ArrayList<Integer>(); final Map<Integer, Integer> countMap = new HashMap<Integer, Integer>(); int max = -1; for (final int n : numbers) { int count = 0; if (countMap.containsKey(n)) { count = countMap.get(n) + 1; } else { count = 1; } countMap.put(n, count); if (count > max) { max = count; } } for (final Map.Entry<Integer, Integer> tuple : countMap.entrySet()) { if (tuple.getValue() == max) { modes.add(tuple.getKey()); } } return modes; }

ADDITION

如果您使用的是Java 8或更高版本,您还可以确定以下模式:

If you are using Java 8 or higher, you can also determine the modes like this:

public static List<Integer> getModes(final List<Integer> numbers) { final Map<Integer, Long> countFrequencies = numbers.stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); final long maxFrequency = countFrequencies.values().stream() .mapToLong(count -> count) .max().orElse(-1); return countFrequencies.entrySet().stream() .filter(tuple -> tuple.getValue() == maxFrequency) .map(Map.Entry::getKey) .collect(Collectors.toList()); }

更多推荐

如何从一组数字计算平均值,中位数,模式和范围

本文发布于:2023-10-20 08:47:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1510493.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中位数   平均值   模式   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!