How to calculate mean, median, mode and range from a set of numbers in java

How to calculate mean, median, mode and range from a set of numbers in java

To calculate the mean, median, mode, and range from a set of numbers in Java, you can create methods to perform these calculations. Here's how you can do it:

  1. Calculate the Mean (Average):

    To calculate the mean (average) of a set of numbers, add up all the numbers and then divide by the total count of numbers.

    public static double calculateMean(double[] numbers) { double sum = 0.0; for (double num : numbers) { sum += num; } return sum / numbers.length; } 
  2. Calculate the Median:

    The median is the middle value of a sorted list of numbers. If there is an even number of values, it's the average of the two middle values.

    import java.util.Arrays; public static double calculateMedian(double[] numbers) { Arrays.sort(numbers); int middle = numbers.length / 2; if (numbers.length % 2 == 0) { return (numbers[middle - 1] + numbers[middle]) / 2.0; } else { return numbers[middle]; } } 
  3. Calculate the Mode:

    The mode is the number that appears most frequently in a set of values.

    import java.util.HashMap; import java.util.Map; public static double calculateMode(double[] numbers) { Map<Double, Integer> frequencyMap = new HashMap<>(); double mode = Double.NaN; int maxFrequency = 0; for (double num : numbers) { int frequency = frequencyMap.getOrDefault(num, 0) + 1; frequencyMap.put(num, frequency); if (frequency > maxFrequency) { maxFrequency = frequency; mode = num; } } return mode; } 
  4. Calculate the Range:

    The range is the difference between the maximum and minimum values in the set.

    public static double calculateRange(double[] numbers) { if (numbers.length == 0) { return Double.NaN; } double min = numbers[0]; double max = numbers[0]; for (double num : numbers) { if (num < min) { min = num; } if (num > max) { max = num; } } return max - min; } 

You can then call these methods with your set of numbers to calculate the mean, median, mode, and range. For example:

public static void main(String[] args) { double[] numbers = { 5, 2, 9, 2, 6, 1, 5, 8, 2, 3 }; double mean = calculateMean(numbers); double median = calculateMedian(numbers); double mode = calculateMode(numbers); double range = calculateRange(numbers); System.out.println("Mean: " + mean); System.out.println("Median: " + median); System.out.println("Mode: " + mode); System.out.println("Range: " + range); } 

This code will calculate and print the mean, median, mode, and range for the set of numbers provided.


More Tags

ios4 cp procedure roles android-holo-everywhere jsonresult windows-phone-7 bootstrap-5 react-datepicker rest

More Java Questions

More Internet Calculators

More General chemistry Calculators

More Investment Calculators

More Bio laboratory Calculators