2

I am developing an application that requires fast accessing of sin/cos/tan values. Are the values provided by math precomputed or computed on the fly?

amtra5
  • 31
  • 2
  • 4

2 Answers2

8

No. Lua simply wraps the standard C sin/cos functions - see lmathlib.c1

Using a look-up table only works for a relatively small discrete set of inputs and is not a general solution for such continuous functions.


1 The code for these wrapper functions follows the form

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

As far as how the standard C functions are implemented, see How does C compute sin() and other math functions?

Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220
4

Consider making these functions local, as in

local sin = math.sin

After this, if you have measured it and it is not fast enough, then consider cacheing the values, if you frequently use the same inputs:

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)
lhf
  • 70,581
  • 9
  • 108
  • 149