计算百分位数
您已经计算了样例咖啡销售中交易金额的平均值、最小值和最大值。现在请计算交易金额的中位数、25 百分位和 75 百分位,并格式化为保留两位小数。
| date | coffee_name | payment_method | quantity | amount |
|---|---|---|---|---|
| 3/1/24 | Latte | cash | 1 | $6.26 |
| 3/5/24 | Hot Chocolate | card | 3 | $32.51 |
| 3/6/24 | Americano | card | 2 | $18.70 |
所需的包,例如 LocalDate、Arrays、List 和 DescriptiveStatistics,已为您导入。
本练习是课程的一部分
Java 数据清洗
练习说明
- 计算咖啡销售中交易金额的中位数(第 50 百分位)。
- 计算交易金额的第 25 百分位和第 75 百分位。
交互式实操练习
通过完成这段示例代码来试试这个练习。
public class CoffeeSalesExample {
private record CoffeeSales(LocalDate date, String coffeeName,
String paymentMethod, int quantity, double amount) {
}
public static void main(String[] args) {
List sales = Arrays.asList(
new CoffeeSales(LocalDate.of(2024, 3, 1), "Latte", "cash", 1, 6.26),
new CoffeeSales(LocalDate.of(2024, 3, 5), "Hot Chocolate", "card", 3, 32.51),
new CoffeeSales(LocalDate.of(2024, 3, 6), "Americano", "card", 2, 18.70));
DescriptiveStatistics stats = new DescriptiveStatistics();
sales.forEach(sale -> stats.addValue(sale.amount()));
System.out.printf("\nSales analyzed: %d%n", sales.size());
System.out.printf("Average amount: $%.2f%n", stats.getMean());
System.out.printf("Amount range: $%.2f - $%.2f%n",
stats.getMin(), stats.getMax());
// Compute the median transaction amount
System.out.printf("Median amount: $%.2f%n", stats.____(____));
// Compute the 25th and 75th percentiles of the amounts
System.out.printf("Normal range: $%.2f - $%.2f%n",
stats.____(____), stats.____(____));
}
}