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

我正在开发一个需要快速访问 sin/cos/tan 值的应用程序。这些值是提前计算好的还是动态计算的?

点赞
用户2864740
用户2864740

不。Lua 只是简单地封装了标准 C 的 sin/cos 函数 - 参见 lmathlib.c1。

使用查找表(look-up table)只对一组有限的、离散的输入有效,并不是对于连续函数的通用解决方案。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?

2014-05-28 00:32:09
用户107090
用户107090

考虑将这些函数设为局部函数,如下:

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)
2014-05-28 11:23:12