Post Reply 
[VA] Short & Sweet Math Challenge #24: "2019 Spring Special 5-tier"
04-08-2019, 03:36 PM (This post was last modified: 04-10-2019 02:41 AM by Albert Chan.)
Post: #30
RE: [VA] Short & Sweet Math Challenge #24: "2019 Spring Special 5-tier"
I posted cin(x) puzzle to the Lua mailing list, and got an elegant solution from Egor Skriptunoff.
Taylor coefficients built on the fly, without any need for CAS. Smile
http://lua-users.org/lists/lua-l/2019-04/msg00063.html

Below code modified a bit for speed, accuracy, and extended cin(x) for tin(x):

Quote:local sin, asin = math.sin, math.asin

local function g(k, m, c, a)     -- assume c[0] = 1, m = [0,999]
    if k < 2 then return c[m] end
    local i = 1000 * k + m
    local r = a[i]
    if r then return r end
    r = g(k-1, m, c, a) + c[m] -- case for j=0 and j=m
    for j = 1, m-1 do
        r = r + c[j] * g(k-1, m-j, c, a)
    end
    a[i] = r
    return r
end

local function f(d, c, a)
    local r = 0
    for j = 1, #c do
        r = r + d[j] * g(2*j+1, #c+1-j, c, a)
    end
    return r
end

function maclaurin_of_cin()
    local c, c2, s = {}, {}, 1
    return function(k)
        for n = #c + 1, k do
            s = -(2*n)*(2*n+1)*s
            local a = {}
            local r, r2 = f(c, c, a), f(c2, c, a)
            local t = (1/s-r-r2)/3
            c[n], c2[n] = t, r + 2*t
        end
        return c[k]
    end
end

function maclaurin_of_tin()
    local c, s = {}, 1
    return function(k)
        for n = #c + 1, k do
            s = -(2*n)*(2*n+1)*s
            c[n] = (1/s - f(c, c, {})) / 2
        end
        return c[k]
    end
end

function egor(x)
    if x*x > 0.25 then return asin(egor(sin(x))) end
    local r, p, s, n, R = 0, x, x*x, 0
    repeat
        R, n, p = r, n+1, p*s
        r = r + maclaurin_coefs(n) * p
    until r == R
    return r + x
end

lua> maclaurin_coefs = maclaurin_of_tin()
lua> for i=50,125,25 do    -- match post #28 Coefs
:      print(2*i+1, maclaurin_coefs(i))
:      end
101  0.08337562280550574
151  388536047335.2163
201  6.555423874650777e+027
251  -3.536522049267692e+046

lua> function nest(f,x,n) for i=1,n do x=f(x);print(i, x) end end
lua> nest(egor, 2.019, 2) -- egor = tin
1      0.9894569770589354
2      0.9012269893998129

lua> maclaurin_coefs = maclaurin_of_cin()
lua> nest(egor, 2.019, 3) -- egor = cin
1      1.0269233186935764
2      0.9566289299961186
3      0.9012269893998129

lua> math.sin(2.019)
0.9012269893998126
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: [VA] Short & Sweet Math Challenge #24: "2019 Spring Special 5-tier" - Albert Chan - 04-08-2019 03:36 PM



User(s) browsing this thread: 1 Guest(s)