This package provides classes and methods for approximating functions or data using rational functions in Python. It includes algorithms for both discrete and continuous approximation, as well as tools for working with various representations of rational functions. It presents a Pythonic interface to the functionality provided by the Julia package RationalFunctionApproximation.jl, which is the computational engine. Julia and the necessary dependencies are installed automatically when you first import pyratapprox.
Installation
You can install the package using pip:
pip install pyratapprox
Examples
Here are some simple examples of how to use the package:
from pyratapprox import approximate, unitintervalimport numpy as npdef f(x):return x + np.tanh(20* (x +0.25))r = approximate(f, unitinterval)print("Approximant of rational type", r.degrees())
Detected IPython. Loading juliacall extension. See https://juliapy.github.io/PythonCall.jl/stable/compat/#IPython
Approximant of rational type (17, 17)
The constructed object can be called like a function to evaluate the approximant:
import matplotlib.pyplot as pltx = np.linspace(-1, 1, 1000)plt.plot(x, r(x))plt.ylabel('r(x)')plt.title('Rational approximant');
By default, the approximant is constructed to achieve an accuracy of about \(10^{-14}\), as seen here:
import matplotlib.pyplot as pltplt.plot(x, f(x) - r(x))plt.ylabel('f(x) - r(x)')plt.title('Pointwise error');
If no method is specified, a Thiele continued fraction (TCF) approximant is constructed:
r.getfunction()
Thiele continued fraction of type (17, 17)
You can instead request the AAA algorithm, which produces a barycentric rational approximant. The method is given as the final positional argument, as in the Julia package, or as the method keyword:
from pyratapprox import AAAapproximate(f, unitinterval, AAA).getfunction()
Barycentric rational function of type (17, 17)
There is often not much to separate the two methods, but as the total degree \(n\) increases, AAA is an \(O(n^4)\) algorithm, while the Thiele method is \(O(n^3)\).
Every approximation records why its iteration stopped:
print(r.isconverged())r.status
True
Stopped by converged after 35 iterations with estimated error 7.105e-14