Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading