# Partial differentiation

I am trying to compute a partial differentiation of the sum of 3 utility functions (u0 + u1 + u2) with respect to s_t0. Is this the right way to do that in SageMath?

w = var('w');
tau_t0 = var('tau_t0'); tau_t1 = var('tau_t1');
s_t0 = var('s_t0'); s_t1 = var('s_t1')
r = var('r'); n = var('n')
u0 = function ('u0')(w, tau_t0, s_t0)
u1 = function ('u1')(w, tau_t1, s_t1)
u2 = function ('u2') (n, w, tau_t0, r, s_t0, s_t1)

u0(w, tau_t0, s_t0) = w*(1-tau_t0) - s_t0
u1(w, tau_t1, s_t1) = w*(1-tau_t1) - s_t1
u2(n, w, tau_t0, r, s_t0, s_t1) = (1+n)^2 * w * tau_t0 + (1+n) * w * tau_t0 + (1+r)^2 * s_t0 + (1+r) * s_t1

a = diff(u0 (w, tau_t0, s_t0), s_t0)
b = diff(u1 (w, tau_t1, s_t1), s_t0)
c = diff(u2 (n, w, tau_t0, r, s_t0, s_t1), s_t0)

U = a + b + c
U

edit retag close merge delete

Sort by » oldest newest most voted Sure, you can do it that way. You can omit the lines

u0 = function ('u0')(w, tau_t0, s_t0)
u1 = function ('u1')(w, tau_t1, s_t1)
u2 = function ('u2') (n, w, tau_t0, r, s_t0, s_t1)


because the subsequent lines just redefine u0,u1,u2 using Sage syntax for function definition.

You could also replace the functions u0,u1,u2 by their values (since you only use the values):

var('w,tau_t0,tau_t1,s_t0,s_t1,r,n')

u0 = w*(1-tau_t0) - s_t0
u1 = w*(1-tau_t1) - s_t1
u2 = (1+n)^2 * w * tau_t0 + (1+n) * w * tau_t0 + (1+r)^2 * s_t0 + (1+r) * s_t1

a = diff(u0, s_t0)
b = diff(u1, s_t0)
c = diff(u2, s_t0)

U = a + b + c
U


Since partial differentiation is linear, you can also define U in terms of u0,u1,u2 in one step:

U = diff(u0+u1+u2, s_t0)

more

Thank you for your answer. I think I have a problem here with the chain rule, that's why I defined u0, u1 and u2 as (utility) functions. For example, the right answer to diff(u0, s_t0) is not -1 but -u0' (w*(1-tau_t0) - s_t0). How can I take this into account in Sage?

It seems that you mean each of u0,u1,u2 should be a (symbolic, unknown) function of one argument (contrary to the code you wrote). Here is how you can do that:

var('w,tau_t0,tau_t1,s_t0,s_t1,r,n')

u0 = function('u0')
u1 = function('u1')
u2 = function('u2')

a = diff(u0(w*(1-tau_t0) - s_t0), s_t0)
b = diff(u1(w*(1-tau_t1) - s_t1), s_t0)
c = diff(u2((1+n)^2 * w * tau_t0 + (1+n) * w * tau_t0 + (1+r)^2 * s_t0 + (1+r) * s_t1), s_t0)

U = a + b + c
U


You're right. I didn't express it well. Now the result is what I expected. Thank you.