lua-users home
lua-l archive

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


Luis Carvalho wrote:
>> -- foo/math.lua
>> module(..., package.seeall)
>> function poly(coefs, x)
>>    local fx = 0
>>    for i,coef in ipairs(coefs) do
>>        fx = fx + coef * x^i
>>    end
>> end
>> --------
> 
> A little off the topic, but this is a bit faster (the coeffs are
> assumed to be in decreasing power order): 
> 
> -- foo/math.lua
> module(..., package.seeall)
> function poly(coefs)
>   return function(x) -- Horner's evaluation
>     local fx = 0
>     for i, coef in ipairs(coefs) do
>       fx = fx * x + coef
>     end
>     return fx
>   end
> end
> --------
> -- foo/physics.lua
> module(..., package.seeall)
> local math = require(_PACKAGE.math)
> g = math.poly{1,2,3} -- x^2+2*x+3

I was aware of that optimisation and almost did it myself (btw my
original implementation has coeffs in increasing order), but optimizing
a purely hypothetical example would just make my point harder to
understand. Simplicity and redundancy (here a simple name + a naive
'straight-from-the-book' implementation) hides less important parts and
help focus on the important ones (in that case the module usage). Anyway
I wondered if someone would fix it when I pressed the send button. I
guess fishing is not as hard as they say :-)