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, ...)
    end
    return mean
end

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

On Tue, Jun 22, 2010 at 3:14 AM, David Manura <dm.lua@math2.org> wrote:
On Mon, Jun 21, 2010 at 8:30 PM, Jonathan Castello <twisolar@gmail.com> 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
   end
   return mean
 end

[1] http://docs.python.org/library/math.html#math.fsum
[2] http://en.wikipedia.org/wiki/Compensated_summation