Can't find out how to compute derivative

73 Views Asked by At

Yo, guys, I got a question, is there any way to improve this or maybe better way to calculate it? Because the only way to calculate derivative very accurate I can think of is this.. lol, its just logic like d/dx of x^n = nx^(n-1) so I thought of that and tried it out, tho doesnt work with functions like e^x so I need help with make a very accurate derivative calculation

function derivative(Function, x)    
    local dxlog = math.log(Function(x), x) 
       
    return dxlog * x^(dxlog - 1)
end 
print(derivative(function(x) return x^3 end, 10))

and its so bad it cant even calculate y^x with respect to x..

tried everything I can think of, too dumb to fix this

btw this is the old way I did this:

function derivative(Function, x)
    local d = (Function(x + 6.7219579999763e-006) - Function((x - 6.7219579999763e-006))) / 1.3443915999953e-005
    if math.abs(math.round(d) - d) < 4.1212121212e-6 then 
        return math.round(d)
    end
    return d
end
1

There are 1 best solutions below

1
Alexander Mashin On

I presume, you want to get numerical derivative, not symbolic. Then why not use the most straightforward approach?

-- 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, left)
    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, left)
    end
end

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

local df = derivative (f)

for _, x in ipairs {-3, -2, -1, 0, 1, 2, 3} do
    print (x, df (x))
end

or simplified:

local delta = 1e-9

local function derivative (f)
    return function (x)
        return (f (x + delta) - f (x)) / delta
    end
end

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

local df = derivative (f)

for _, x in ipairs {-3, -2, -1, 0, 1, 2, 3} do
    print (x, df (x))
end