TI-Nspire & Lua / スクリプティングのヒント / クロージャを使う 7 / 演習 9.1: 積分する

-- 演習 9.1: 函数 f を引数に取ってその積分の近似値を返す函数 integral を作れ。
-- Exercise 9.1: Write a function _integral_ that takes a function _f_ and returns an approximation of its integral.
local function integral(f)
   return function(from, to, dx, init)
              local sum = init or 0
              for x = from, to, dx do
                 --sum = sum + f(x) * dx -- 区分求積法で求める。
                 sum = sum + (f(x) + f(x + dx)) * dx / 2 -- 臺形公式で求める。
              end
              return sum
           end
end

----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
local P = math.pi
local function square    (x) return x^2 end
local function reciprocal(x) return 1/x end
print(integral(math.exp  )(0, 2, 0.1, 1))
print(integral(math.sin  )(0, P, 0.1, 0))
print(integral(square    )(0, 2, 0.1, 0))
print(integral(reciprocal)(1, 3, 0.1, 0))

f:id:ti-nspire:20170205133245p:plain:h250 f:id:ti-nspire:20170205133712p:plain:h250
 
参考: