I have a function
that I want to simplify and differentiate in Python, defined as**
def u(x, t):
return math.erf((x + 1) / (2 * (k * t) ** (1 / 2)))
** Please correct me if I am wrong.
I have all the necessary imports as follows:
import math
import scipy
import matplotlib
from sympy import *
As well as defining the symbols
x, k, t = symbols('x k t')
This works perfectly fine:
def f(x):
return x ** 4
diff(f(x))
Which returns the correct answer,
4x^3
However, this
diff(u(x, t))
or this
diff(u(x, t), t)
returns an error as follows
TypeError Traceback (most recent call last) in () ----> 1 diff(u(x, t))
in u(x, t) 1 def u(x, t): ----> 2 return math.erf((x + 1) / (2 * (k * t) ** (1 / 2)))
C:\Anaconda\lib\site-packages\sympy\core\expr.py in float(self) 223 if result.is_number and result.as_real_imag()1: 224 raise TypeError("can't convert complex to float") --> 225 raise TypeError("can't convert expression to float") 226 227 def complex(self):
TypeError: can't convert expression to float
In Matlab I could easily do it:
syms x;
syms k;
syms t;
u = erf((x + 1)/(2 * sqrt(k * t)));
LHS = simplify(diff(u, t))
RHS = k * simplify(diff(u, x, 2))
My question is, how can I differentiate and/or simplify a mathematical function of more than one variable in Python?
You need to use sympy.erf
, not math.erf
:
>>> import sympy
>>> x, k, t = sympy.symbols('x k t')
>>> def u(x, t):
... return sympy.erf((x + 1) / (2 * (k * t) ** (1 / 2)))
>>> sympy.diff(u(x, t), x, t)
(0.25*(k*t)**(-1.5)*(x + 1)**2 - 0.5*(k*t)**(-0.5))*exp(-(k*t)**(-1.0)*(x + 1)**2/4)/(sqrt(pi)*t)