[PATCH 1/3] Simplify/clarify the get_surface_pressure_in_mbar() function

Linus Torvalds torvalds at linux-foundation.org
Fri Feb 8 16:48:03 PST 2013


From: Linus Torvalds <torvalds at linux-foundation.org>
Date: Sat, 9 Feb 2013 10:23:15 +1100
Subject: [PATCH 1/3] Simplify/clarify the get_surface_pressure_in_mbar() function

Instead of maintaining a rolling average and re-calculating it at each
stage, just calculate the surface_pressure average the natural way: as
the sum divided by the number of entries.

This results in a single rounding, rather than doing rounding multiple
times and possibly rounding wrong as a result.

Not that we care all that deeply about the LSB of the mbar value, but
the code is simpler and more obvious this way too.

Signed-off-by: Linus Torvalds <torvalds at linux-foundation.org>
---

The next few patches will change this more, so the lines get moved around 
etc, but the change to the basic algorithm is conceptually a different 
thing..

 dive.c       | 25 +++++++++++++++----------
 statistics.c |  7 ++++---
 2 files changed, 19 insertions(+), 13 deletions(-)

diff --git a/dive.c b/dive.c
index 7083e857c03b..cbee208ec7e6 100644
--- a/dive.c
+++ b/dive.c
@@ -232,18 +232,23 @@ int get_duration_in_sec(struct dive *dive)
 
 int get_surface_pressure_in_mbar(const struct dive *dive, gboolean non_null)
 {
-	int count = 0, pressure = 0;
+	unsigned int count = 0, sum = 0;
 	const struct divecomputer *dc = &dive->dc;
+
 	do {
-		if (dc->surface_pressure.mbar) {
-			pressure = (double)(count * pressure + dc->surface_pressure.mbar) / (count + 1) + 0.5;
-			count++;
-		}
-		dc = dc->next;
-	} while (dc);
-	if (!pressure && non_null)
-		pressure = SURFACE_PRESSURE;
-	return pressure;
+		if (!dc->surface_pressure.mbar)
+			continue;
+		sum += dc->surface_pressure.mbar;
+		count++;
+	} while ((dc = dc->next) != NULL);
+
+	/* Did we have any dive computers with surface pressure information */
+	if (count)
+		return (sum + count/2) / count;
+
+	if (non_null)
+		return SURFACE_PRESSURE;
+	return 0;
 }
 
 static void update_temperature(temperature_t *temperature, int new)
diff --git a/statistics.c b/statistics.c
index 82070a937479..d7abbc592483 100644
--- a/statistics.c
+++ b/statistics.c
@@ -539,7 +539,7 @@ static void show_single_dive_stats(struct dive *dive)
 	double value;
 	int decimals;
 	const char *unit;
-	int idx, offset, gas_used;
+	int idx, offset, gas_used, mbar;
 	struct dive *prev_dive;
 	struct tm tm;
 
@@ -579,8 +579,9 @@ static void show_single_dive_stats(struct dive *dive)
 	} else {
 		set_label(single_w.air_temp, "");
 	}
-	if (get_surface_pressure_in_mbar(dive, FALSE)) {
-		set_label(single_w.air_press, "%d mbar", dive->dc.surface_pressure.mbar);
+	mbar = get_surface_pressure_in_mbar(dive, FALSE);
+	if (mbar) {
+		set_label(single_w.air_press, "%d mbar", mbar);
 	} else {
 		set_label(single_w.air_press, _("unknown"));
 	}
-- 
1.8.1.3.535.ga923c31



More information about the subsurface mailing list