Warning: this is an htmlized version!
The original is here, and the conversion rules are here. |
-- This file: -- http://anggtwu.net/LUA/integrate-2015.lua -- http://anggtwu.net/LUA/integrate-2015.lua.html -- (find-angg "LUA/integrate-2015.lua") -- integrate_left = function (f, a, b) return (b-a)*f(a) end integrate_right = function (f, a, b) return (b-a)*f(b) end integrate_trapeze = function (f, a, b) return (b-a)*(f(a)+f(b))/2 end integrate_simpson = function (f, a, b) local m = (a+b)/2 local ht = (f(a)+f(b))/2 -- height of the trapeze local hp = f(m) - ht -- height of the parabola above the trapeze local at = (b-a)*(f(a)+f(b))/2 -- area of the trapeze local ap = (b-a)*hp*(2/3) -- area of the parabola above the trapeze return at+ap end integrate = integrate_left integrate_n = function (f, a, b, n) local ai = function (i) return a + (b-a)*i/n end local total = 0 for i=0,n-1 do total = total + integrate(f, ai(i), ai(i+1)) end return total end --[[ * (eepitch-lua51) * (eepitch-kill) * (eepitch-lua51) dofile "integrate-2015.lua" integrate = integrate_left integrate = integrate_right integrate = integrate_trapeze integrate = integrate_simpson f = function (x) return x end print(integrate_n(f, 0, 2, 10)) integrate = integrate_simpson f = function (x) return math.sin(x) end print(integrate_n(f, 0, math.pi/2, 5)) print(integrate_n(f, 0, math.pi/2, 10)) print(integrate_n(f, 0, math.pi/2, 20)) print(integrate_n(f, 0, math.pi/2, 40)) print(integrate_n(f, 0, math.pi/2, 80)) --]] -- Local Variables: -- coding: raw-text-unix -- End: