Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
like image 988
user121416 Avatar asked May 09 '26 23:05

user121416


1 Answers

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
like image 152
Anton Avatar answered May 11 '26 13:05

Anton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!