Модуль:Derivative

Для документации этого модуля может быть создана страница Модуль:Derivative/doc

-- lim_{x -> x0} f(x):
local function limit (f, x0, left)
	local x0 = x0 or 0
	local y0 = f (x0)
	if y0 == y0 --[[ not NaN, i.e. 0/0 ]] then
		-- Simplest case: lim_{x -> x0} f(x) = f (x0) (not for derivative, anyway):
		return y0
	end
	local abs = math.abs
	local delta_x = left and -2e-9 or 2e-9
	local y, y1, y2 -- old values of f (x).
	-- Halve delta_x while it is measureable or until f(x) starts to lose accuracy:
	while not y1 or not y2 or abs (delta_x) > 0 and abs (y - y1) < abs (y1 - y2) do
		delta_x = delta_x / 2
		-- Remember changes of y:
		y, y1, y2 = f (x0 + delta_x), y, y1
	end
	return y
end

-- f'(x):
local function derivative (f)
	return function (x)
		-- f'(x) = lim_{delta -> 0} (f (x + delta) - f(x)) / delta:
		return limit (function (delta)
			return (f (x + delta) - f (x)) / delta
		end, --[[ delta -> ]] 0)
	end
end

-- Example:
local f = function (x)
	return x ^ 3
end

local df = derivative (f)

return {
	test = function (frame)
		local tbl = {}
		for _, x in ipairs {-3, -2, -1, 0, 1, 2, 3} do
			tbl [#tbl + 1] = tostring (x) .. '\t' .. tostring (df (x))
		end
		return table.concat (tbl, '\n')
	end
}