Apply simplification rule for special functions
I am defining two custom functions in Sympy called phi
and phi
. I know that Phi(x)+Phi(-x) == 1
. How do you provide Sympy with this simplification rule? Can I specify this in the class definition?
Here's what I've done so far:
from sympy import Function
class phi(Function):
nargs = 1
def fdiff(self, argindex=1):
if argindex == 1:
return -1*self.args[0]*phi(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
# The function is even, so try to pull out factors of -1
if arg.could_extract_minus_sign():
return cls(-arg)
class Phi(Function):
nargs = 1
def fdiff(self, argindex=1):
if argindex == 1:
return phi(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
For the curious, phi
and phi
are Gaussian PDF and CDF, respectively. They are implemented in sympy.stats
. But, in my case, it is easier to interpret the results in terms of phi
and phi
.
source to share
Based on Stelios' comment, Phi(x)
should return 1-Phi(-x)
if x
negative. So I modified Phi
as follows:
class Phi(Function):
nargs = 1
def fdiff(self, argindex=1):
if argindex == 1:
return phi(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
# Phi(x) + Phi(-x) == 1
if arg.could_extract_minus_sign():
return 1-cls(-arg)
source to share