TI-Nspire & Lua / 古典的ルンゲクッタ法 3 / クロージャを使って初期値を更新しながら 1 ステップずつの計算を繰り返す

function rk(func, t0, x0, step)
   local t0, x0 = t0, x0
   
   local stepDiv2  = step / 2
   local stepDiv6  = step / 6
   local halfPoint = t0 + stepDiv2
   
   local f1, f2, f3, f4

   return function()
              f1 = func(t0        , x0                )
              f2 = func(halfPoint , x0 + stepDiv2 * f1)
              f3 = func(halfPoint , x0 + stepDiv2 * f2)
              f4 = func(t0 + step , x0 + step     * f3)

              t0        = t0 + step
              x0        = x0 + stepDiv6 * (f1 + 2 * (f2 + f3) + f4)
              halfPoint = t0 + stepDiv2

              return t0, x0
           end
end

-- 確かめる。
function sute(t, x)
   return x^2 - t^2 - 2 * t + 2
end

rk1 = rk(sute, 0, 0, 1/8) -- 初期値のセットされた函数を作って、
for i = 1, 8 do
   print(rk1()) -- その初期値を更新しながら計算を繰り返す。
end

f:id:ti-nspire:20170502143727p:plain