From d2f4defee20c19d4b401dd47c3f23ff57beed33e Mon Sep 17 00:00:00 2001 From: "Wojciech A. Koszek" Date: Thu, 23 Feb 2006 20:46:10 +0000 Subject: [PATCH] Fix the way in which median is calculated. If the data source has even number of data points, value should be calculated by adding two middle elements and dividing them by 2. Approved by: cognet (mentor) --- tools/tools/ministat/ministat.c | 25 ++++++++++++++++++------- usr.bin/ministat/ministat.c | 25 ++++++++++++++++++------- 2 files changed, 36 insertions(+), 14 deletions(-) diff --git a/tools/tools/ministat/ministat.c b/tools/tools/ministat/ministat.c index 038ef6b5acfe..af3f803b88d6 100644 --- a/tools/tools/ministat/ministat.c +++ b/tools/tools/ministat/ministat.c @@ -202,15 +202,26 @@ Avg(struct dataset *ds) static double Median(struct dataset *ds) { - int i; - struct point *pp; + int even, i; + struct point *p1, *p2; - i = ds->n / 2; - TAILQ_FOREACH(pp, &ds->list, list) { - if (i--) - continue; - return (pp->val); + if ((ds->n % 2) == 1) { + i = (ds->n / 2) + 1; + even = 0; + } else { + i = ds->n / 2; + even = 1; } + TAILQ_FOREACH(p1, &ds->list, list) { + --i; + if (i == 0) + break; + } + if (even) { + p2 = TAILQ_NEXT(p1, list); + return ((p2->val + p1->val) / 2); + } + return (p1->val); } static double diff --git a/usr.bin/ministat/ministat.c b/usr.bin/ministat/ministat.c index 038ef6b5acfe..af3f803b88d6 100644 --- a/usr.bin/ministat/ministat.c +++ b/usr.bin/ministat/ministat.c @@ -202,15 +202,26 @@ Avg(struct dataset *ds) static double Median(struct dataset *ds) { - int i; - struct point *pp; + int even, i; + struct point *p1, *p2; - i = ds->n / 2; - TAILQ_FOREACH(pp, &ds->list, list) { - if (i--) - continue; - return (pp->val); + if ((ds->n % 2) == 1) { + i = (ds->n / 2) + 1; + even = 0; + } else { + i = ds->n / 2; + even = 1; } + TAILQ_FOREACH(p1, &ds->list, list) { + --i; + if (i == 0) + break; + } + if (even) { + p2 = TAILQ_NEXT(p1, list); + return ((p2->val + p1->val) / 2); + } + return (p1->val); } static double