Chebyshev approximation is very useful if one needs repeated evaluation of an expensive function, such as function defined implicitly by an integral or a differential equation. (In particular, it provides the opportunity to turn a slow mpmath function into a fast machine-precision version of the same.)
chebyfit(f, [a, b], N) generates a polynomial of degree N-1 that approximates f on the finite interval [a, b] and returns a list containing the polynomial coefficients. With error=True, it also returns a number estimating the maximum error on the interval.
Here we use it to generate a low-degree approximation of f(x) = cos(x), valid on the interval [1, 2]:
>>> from mpmath import *
>>> poly, err = chebyfit(cos, [1, 2], 5, error=True)
>>> nprint(poly)
[2.91682e-3, 0.146166, -0.732491, 0.174141, 0.949553]
>>> nprint(err, 12)
1.61351758081e-5
The polynomial can be evaluated using polyval:
>>> nprint(polyval(poly, 1.6), 12)
-0.0291858904138
>>> nprint(cos(1.6), 12)
-0.0291995223013
Sampling the true error at 1000 points shows that the error estimate automatically generated by chebyfit is remarkably good:
>>> error = lambda x: abs(cos(x) - polyval(poly, x))
>>> nprint(max([error(1+n/1000.) for n in range(1000)]), 12)
1.61349954245e-5
The degree N can be set arbitrarily high, to obtain an arbitrarily good approximation. As a rule of thumb, an N-term Chebyshev approximation is good to N/(b-a) decimal places (although this depends on how well-behaved f is). The cost grows accordingly: chebyfit evaluates the function (N^2)/2 times to compute the coefficients and an additional N times to estimate the error.
One should be careful to use a sufficiently high working precision both when calling chebyfit and when evaluating the resulting polynomial, as the polynomial is sometimes ill-conditioned. It is for example difficult to reach 15-digit accuracy when evaluating the polynomial using machine precision floats, no matter the theoretical accuracy of the polynomial. (The option to return the coefficients in Chebyshev form should be made available in the future.)
It is important to note the Chebyshev approximation works poorly if f is not smooth. A function containing singularities, rapid oscillation, etc can be approximated more effectively by multiplying it with a weight function that cancels out the nonsmooth features.