Search code examples
pythonnumerical-methods

Differentiating a multivariable function w.r.t different dimensions, using *args in python


Following is my attempt to create a function to differentiate multivariable functions, but as you see it only seems to be able to differentiate with respect to the first positional argument (namely x). How can I extend this to be able to take partial derivatives with respect to y and z?

def firstderivative(func,x,*args):
    return((func(x+0.001,*args)-func(x-0.001,*args))/0.002)
def afunc(x,y,z):
    return(x*y+x*z+y*z)
print(firstderivative(afunc,2,4,5))

Solution

  • You can treat args as a list, after converting it from tuple.

    def firstderivative(func, n, *args):
        # args[0] is x, args[1] is y and args[2] is z
        args_0 = list(args)
        args_0[n] -= 0.001
    
        args_1 = list(args)
        args_1[n] += 0.001
    
        return ((func(*args_1) - func(*args_0)) / 0.002)
    
    
    def afunc(x, y, z):
        return (x * y + x * z + y * z)
    
    print(firstderivative(afunc, 0, 2, 4, 5))  # x
    print(firstderivative(afunc, 1, 2, 4, 5))  # y
    print(firstderivative(afunc, 2, 2, 4, 5))  # z