Partial Derivative with sympy Python

3.7k Views Asked by At

I used Python's sympy to take the partial derivative of the following function with respect to $\rho$:

$$f = \frac{V\lambda(k\rho)^k}{2k!k^2\rho(1-\rho)^2 \left [\sum_{n=0}^{k-1}\frac{(k\rho)^n}{n!}+\frac{(k\rho)^k}{k!(1-\rho)} \right ]}$$

import sympy as sy
sy.init_printing()
from sympy import Sum, collect, factorial
V, lambdaa,rho = sy.symbols('V lambda rho', real=True)
n, k = sy.symbols('n k', integer= True)
f = (V*lambdaa*(k*rho)**k / (2*sy.factorial(k)*k**2*rho*(1-rho)**2
            *(sy.Sum((k*rho)**n/sy.factorial(n), (n,0,k-1)) 
              + (k*rho)**k/(sy.factorial(k)*(1-rho)))))
(collect(collect(sy.simplify(sy.diff(f, rho)), Sum(k**n*rho**n/factorial(n),
        (n, 0, k - 1)), lambda i: collect(i, k)), 
         Sum(k**n*rho**n*n/rho/factorial(n), (n, 0, k - 1)), 
         lambda i: collect(i, rho**k)))

It yields:

$$\frac{\partial f}{\partial \rho}=\frac{V \lambda \left(k \rho\right)^{k - 2}}{2 \left(\rho - 1\right)^{2} \left(- k^{k} \rho^{k} + \left(\rho k! - k!\right) \sum_{n=0}^{k - 1} \frac{k^{n} \rho^{n}}{n!}\right)^{2}} \left(2 k^{k} \rho^{k + 1} - \left(k \rho\right)^{k} + \left(- \rho^{3} k! + 2 \rho^{2} k! - \rho k!\right) \sum_{n=0}^{k - 1} \frac{k^{n} n \rho^{n}}{\rho n!} + \left(k \left(\rho^{2} k! - 2 \rho k! + k!\right) - 3 \rho^{2} k! + 4 \rho k! - k!\right) \sum_{n=0}^{k - 1} \frac{k^{n} \rho^{n}}{n!}\right)$$

Based on the above partial derivative, I want to know if $\frac{\partial f}{\partial \rho}\geq0$ with these conditions: $0<\rho<1$, $V\geq0$, $\lambda \geq 0$, and $k\geq1$. $k$ is integer and all other variables are continuous. I see that the first fraction is positive, however, the rest is not very clear.

1

There are 1 best solutions below

3
On

From a coding point of view, it is always simpler to use for cases like this one logarithmic differentiation. Rewrite your expression $$f = \frac{V\lambda(k\rho)^k}{2k!k^2\rho(1-\rho)^2 \left [\sum_{n=0}^{k-1}\frac{(k\rho)^n}{n!}+\frac{(k\rho)^k}{k!(1-\rho)} \right ]}$$ as $$f=\frac {V\lambda k^k}{2k!k^2}\frac{\rho^{k-1} }{(1-\rho)^2 A}\qquad \text{where} \qquad A=\sum_{n=0}^{k-1}\frac{(k\rho)^n}{n!}+\frac{(k\rho)^k}{k!(1-\rho)} $$ Take logarithms $$\log(f)=\log\left(\frac {V\lambda k^k}{2k!k^2} \right)+(k-1)\log(\rho)-2\log(1-\rho)-\log(A)$$ Differentiate both sides $$\frac {f'}f=\frac{k-1}\rho+\frac 2{1-\rho}-\frac{A'}A$$

$$A'=\sum_{n=0}^{k-1}\frac{(k\rho)^n}{(n-1)!\rho}+\frac{(k \rho )^k (k+\rho-k\rho )}{(\rho -1)^2 \rho k!}$$

To finish, write $$f'=f \times \left(\frac {f'}f\right)$$ and do not simplify at all.

This will give you a much more efficient code.