開始使用免費開始

計算百分位數

你已經計算出樣本咖啡銷售的平均值、最小值與最大值。現在請找出交易金額的中位數、以及第 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

所需的套件(例如 LocalDateArraysListDescriptiveStatistics)已為你匯入。

本練習屬於課程

使用 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.____(____));
    }
}
編輯並執行程式碼