changeset 15465:930117c97760

mean.m: improve geometric mean algorithm for small numbers. Add test.
author Jordi Gutiérrez Hermoso <jordigh@octave.org>
date Mon, 01 Oct 2012 12:38:07 -0400
parents 6a05cad5b694
children ded4ce76ee7a
files scripts/statistics/base/mean.m
diffstat 1 files changed, 8 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/scripts/statistics/base/mean.m
+++ b/scripts/statistics/base/mean.m
@@ -113,7 +113,11 @@
   if (strcmp (opt, "a"))
     y = sum (x, dim) / n;
   elseif (strcmp (opt, "g"))
-    y = prod (x, dim) .^ (1/n);
+    if (all (x(:) >= 0))
+      y = exp (sum (log (x), dim) ./ n);
+    else
+      error ("mean: X must not contain any negative values");
+    endif
   elseif (strcmp (opt, "h"))
     y = n ./ sum (1 ./ x, dim);
   else
@@ -131,6 +135,9 @@
 %! assert (mean (y), 0);
 %! assert (mean (z), [0, 10]);
 
+## Test small numbers
+%!assert (mean (repmat (0.1,1,1000), "g"), 0.1, 20*eps)
+
 %!assert (mean (magic (3), 1), [5, 5, 5])
 %!assert (mean (magic (3), 2), [5; 5; 5])
 %!assert (mean ([2 8], "g"), 4)