lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Wow, for such a seemingly simple function, a lot of people have come up with either really strange implementations or simple but wrong ones.
I like Jeffs and Davids versions though!

Here's a tail recursive version:
local function meanworker(mean, index, x, ...)
    if x then
        return meanworker(mean + (x - mean) / index, index + 1, ...)
    return mean

function mean(...)
    return meanworker(0, 1, ...)

On Tue, Jun 22, 2010 at 3:14 AM, David Manura <> wrote:
On Mon, Jun 21, 2010 at 8:30 PM, Jonathan Castello <> wrote:
> It's really just the average of two numbers, (x+y)/2. An averaging
> function isn't such a bad idea, particularly if it takes an arbitrary
> number of parameters (like Jeff Pohlmeyer's implementation in this
> thread).

For reducing numerical error when summing numbers, see algorithms like
in Python's math.fsum [1] and [2].

This version of mean is less efficient but supports incremental
computation and is less prone to overflow (not that overflow would
likely happen for floating point numbers):

 local function mean(...)
   local mean = 0
   for i=1,select('#', ...) do
     mean = mean + (select(i, ...) - mean) / i
   return mean