java - How to calculate mean, median, mode and range from a set of numbers -
are there functions (as part of math library) calculate mean, median, mode , range set of numbers.
yes, there seem 3rd libraries (none in java math). 2 have come are:
http://www.iro.umontreal.ca/~simardr/ssj/indexe.html
but, not difficult write own methods calculate mean, median, mode , range.
mean
public static double mean(double[] m) { double sum = 0; (int = 0; < m.length; i++) { sum += m[i]; } return sum / m.length; }
median
// array double[] m must 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; } }
mode
public static int mode(int a[]) { int maxvalue, maxcount; (int = 0; < a.length; ++i) { int count = 0; (int j = 0; j < a.length; ++j) { if (a[j] == a[i]) ++count; } if (count > maxcount) { maxcount = count; maxvalue = a[i]; } } return maxvalue; }
update
as has been pointed out neelesh salpe, above not cater multi-modal collections. can fix 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; (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; } } (final map.entry<integer, integer> tuple : countmap.entryset()) { if (tuple.getvalue() == max) { modes.add(tuple.getkey()); } } return modes; }
addition
if using java 8 or higher, can determine modes 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()); }
Comments
Post a Comment