Differentiation example

This demonstrates solving the problem I found here, using the SymEngine gem.


The function is described as $$f_p(x) = \dfrac{9\sqrt{x^2+p}}{x^2+2}$$ We need to differentiate w.r.t. $x$

One solution is: $$f_p^2(x) (x^2 + 2)^2 = 81(x^2 + p) \quad\Longrightarrow$$

$$2 f_p(x) f_p'(x)(x^2 + 2)^2 + 4x f_p^2(x^2 +2) = 162x \quad\Longrightarrow$$\begin{align}f_p'(x) &= \frac{162x - 4x f_p^2(x)(x^2+2)}{2f_p(x)(x^2+2)^2}\\ \\ &= \frac{162x - 324x\frac{x^2 + p}{x^2 +2}}{18(x^2 +2)\sqrt{x^2+p}}\\ \\ &= \frac{9 x (x^2+2) - 18x(x^2+p)}{(x^2 + 2)^2 \sqrt{x^2 + p}}\\ \\ &= \frac{9x(2-2p-x^2)}{(x^2 + 2)^2\sqrt{x^2 + p}}\end{align}

We will attempt to solve this using features in SymEngine



In [1]:
require 'symengine'


Out[1]:
true

Declare the symbols


In [3]:
x = SymEngine::Symbol.new('x')
p = SymEngine::Symbol.new('p')
half = 1.quo(2)


Out[3]:
(1/2)

Create the expression


In [5]:
fp = 9*((x**2 + p)**half)/((x**2)+2)
fp.to_s


Out[5]:
"9*(p + x**2)**(1/2)/(2 + x**2)"

Differentiate wrt $x$


In [8]:
answer = fp.diff(x)
answer.to_s


Out[8]:
"-18*x*(p + x**2)**(1/2)/(2 + x**2)**2 + 9*x/((2 + x**2)*(p + x**2)**(1/2))"

Which is indeed correct! If you simplify the second last answer that we got from our solution. You will find the exact same answer. Using SymEngine for solving problems is as simple as that.