  lua-l archive

• Subject: Re: Suggestion: math.between()
• From: Kristofer Karlsson <kristofer.karlsson@...>
• Date: Tue, 22 Jun 2010 07:56:56 +0200

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 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

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

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

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