I am defining two custom functions in Sympy, called phi and Phi. I know that Phi(x)+Phi(-x) == 1. How do I provide Sympy with this simplification rule? Can I specify this in my class definition?
Here is 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 represent the Gaussian PDF and CDF, respectively. These are implemented in sympy.stats. But, in my case, it's easier to interpret results in terms of phi and Phi.
Based upon the comment by Stelios, Phi(x) should return 1-Phi(-x) if x is negative. Therefore, 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With