Search code examples
pythonfunctionmathscipypolynomial-math

Evaluation of a Chebyshev polynomial


I need to construct a function that provides me with a the value of any Chebyshev polynomial at a point. I have a function that does that for legendre polynomials as

def legendre_Pn(K, x):

    p0 = N.array(1.0)
    p1 = N.array(x)

    if K==0:
        return p0
    elif K==1:
        return p1
    else:
        for n in range(2,K+1):
            pn = (2*n-1)*x*p1/n-(n-1)*p0/n
            p0 = p1
            p1 = pn
        return pn

However, since Chebyshev's are calculated using not the first two but the previous one as can be seen in https://en.wikipedia.org/wiki/Chebyshev_polynomials, I can't do it as in the previous code. I have found the following function https://docs.scipy.org/doc/numpy/reference/generated/numpy.polynomial.chebyshev.chebval.html#numpy.polynomial.chebyshev.chebval, but I don't think it does what I need.


Solution

  • You can use mpmath.chebyt(n, x) for this, where n refers to the Chebyshev polynomial you want to evaluate, and x is the point at which you want to evaluate it.

    The return value is of the class mpf, a real float. More details can be found here.

    Example Usage:

    >>> chebyt(4, 0.5)
    mpf('-0.5')