Search code examples
pythonsympytaylor-series

Computing taylor series of multivariate function with sympy


I am trying to compute with SymPy the taylor series of a function which depends on the trigonomertic function sinc (here), to simplify my problem, we can assume the function I need the Taylor series of is :

f(x1, x2) = sinc(x1) * sinc(x2)

My problem is that when importing sympy.mpmath I often get the error :

cannot create mpf from ...

I have tried to use the taylor-series approximation or this other solution (number 1.), but they all seem to fail. For example for the later alternative the line :

(sinc(x)*sinc(y)).series(x,0,3).removeO().series(y,0,3).removeO()

returns :

cannot create mpf from x

I also have tried of defining the function as an expression and as a lambda function. But nothing seems to work.

Any help will be much appreciated.


Solution

  • You can't use mpmath functions with symbolic SymPy objects. You need to define sinc symbolically.

    One way is to just define it as a Python function that returns the equivalent (here sin is sympy.sin):

    def sinc(x):
        return sin(x)/x
    

    Or, you could write your own SymPy class for it.

    class sinc(Function):
        @classmethod
        def eval(cls, x):
            if x == 0:
                return 1
            # Should also include oo and -oo here
            sx = sin(x)
            # Return only if sin simplifies
            if not isinstance(sx, sin):
                return sx/x
    
        # You'd also need to define fdiff or _eval_derivative here so that it knows what the derivative is
    

    The latter lets you write sinc(x) and it will be printed like that, and you can also define custom behavior with it like what the derivative looks like, how the series works, and so on. This would also let you define the correct values at 0, oo, and so on.

    But for the purposes of taking series, just using sin(x)/x (i.e., the first solution) works fine, because your final answer won't have sinc in it anyway, and the series methods take the limit correctly when evaluating at points like 0.