Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implement simplification rule for special functions

Tags:

sympy

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.

like image 263
Stefan Avatar asked Nov 28 '25 22:11

Stefan


1 Answers

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)
like image 54
Stefan Avatar answered Dec 02 '25 04:12

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!