math.sin / cos / tan是否使用查找表?

时间:2014-05-28 00:28:10

标签: lua

我正在开发一个需要快速访问sin / cos / tan值的应用程序。数学提供的值是否可以预先计算或计算?

2 个答案:

答案 0 :(得分:8)

没有。 Lua简单地包含了标准的C sin / cos函数 - 参见lmathlib.c 1

使用查找表仅适用于相对较小的离散输入集,并不是此类continuous functions的通用解决方案。


1 这些包装函数的代码遵循

形式
static int math_sin (lua_State *L) {
  lua_pushnumber(L, l_tg(sin)(luaL_checknumber(L, 1)));
                      /* ^-- standard lib-C function */
  return 1;
}

就标准C函数的实现方式而言,请参阅 How does C compute sin() and other math functions?

答案 1 :(得分:4)

考虑将这些功能设为本地功能,如

local sin = math.sin

在此之后,如果你已经测量了它并且速度不够,那么考虑缓存这些值,如果你经常使用相同的输入:

local function cache(f)
    local c={}
    return function (x)
        local y=c[x]
        if y==nil then
            y=f(x)
            c[x]=y
        end
        return y
    end
end

local sin = cache(math.sin)
local cos = cache(math.cos)
local tan = cache(math.tan)