Java计算中位数、方差、标准差、众数
时间: 2023-08-07 16:05:56 浏览: 87
java 计算中位数的实现方法
计算中位数:
```java
public static double calculateMedian(double[] values) {
Arrays.sort(values);
int middle = values.length / 2;
if (values.length % 2 == 0) {
double left = values[middle - 1];
double right = values[middle];
return (left + right) / 2;
} else {
return values[middle];
}
}
```
计算方差和标准差:
```java
public static double calculateVariance(double[] values) {
double mean = calculateMean(values);
double sum = 0;
for (double value : values) {
sum += Math.pow(value - mean, 2);
}
return sum / (values.length - 1);
}
public static double calculateStandardDeviation(double[] values) {
return Math.sqrt(calculateVariance(values));
}
private static double calculateMean(double[] values) {
double sum = 0;
for (double value : values) {
sum += value;
}
return sum / values.length;
}
```
计算众数:
```java
public static double calculateMode(double[] values) {
int maxCount = 0;
double mode = Double.NaN;
Map<Double, Integer> valueCount = new HashMap<>();
for (double value : values) {
int count = valueCount.getOrDefault(value, 0) + 1;
valueCount.put(value, count);
if (count > maxCount) {
maxCount = count;
mode = value;
}
}
return mode;
}
```
注意,这里的众数可能不止一个,如果有多个众数,这里只会返回其中一个。
阅读全文