我在Sympy中定义了两个自定义函数,分别称为phi和Phi。我知道那个Phi(x)+Phi(-x) == 1。如何为Sympy提供此简化规则?我可以在我的类定义中指定这个吗?
以下是我到目前为止所做的工作:
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)对于好奇的人来说,phi和Phi分别表示高斯PDF和CDF。这些都是用sympy.stats实现的。但是,在我的例子中,用phi和Phi解释结果更容易。
发布于 2017-05-31 20:30:02
根据Stelios的注释,如果x为负,则Phi(x)应返回1-Phi(-x)。因此,我对Phi进行了如下修改:
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)https://stackoverflow.com/questions/44283354
复制相似问题