This repository generates Fourier Extension coefficients for a user supplied
function. fourier_extension.py uses SciPy's adaptive quad integrator.
--degree fixes the Fourier degree; the script searches for the Hermite order
that gives the best precision at that degree.
python -m pip install -r requirements.txtpython fourier_extension.py --func "FUNCTION_IN_X" \
--left LOWER_BOUND --right UPPER_BOUND --degree DEGREE--degree is the highest Fourier index, so degree 32 produces coefficients
0 through 32. Precision is not an input: for the fixed degree, the script
searches Hermite orders (ke) and reports the one with the smallest mean
Fourier reconstruction error.
Hyperbolic tangent on [-4, 4]:
python fourier_extension.py \
--func "tanh(x)" --left -4 --right 4 --degree 32Sigmoid on [-8, 8]:
python fourier_extension.py \
--func "1/(1+exp(-x))" --left -8 --right 8 --degree 32GELU using the tanh approximation on [-4, 4]:
python fourier_extension.py \
--func "0.5*x*(1+tanh(sqrt(2/pi)*(x+0.044715*x**3)))" \
--left -4 --right 4 --degree 32Pass the original target function in x; interval mapping is performed
internally. Do not manually replace x with a scaled variable such as 64*x.
The command always prints a paste-ready C++ declaration and a comment recording
the selected ke and achieved precision:
// ke: 16, precision: 26.6488 bits
static const inline std::vector<std::complex<double>> coeff_exp_2_double_20{
std::complex<double>(...),
// ...
};The variable name follows coeff_<function>_<interval>_double_<degree>, for
example coeff_tanh_4_double_32, coeff_sigmoid_8_double_32, and
coeff_gelu_4_double_32.
The output coefficients use the a_n - i*b_n convention. The same API is
available from Python:
from fourier_extension import calculate_fourier_coefficients
ke, precision, coefficients = calculate_fourier_coefficients("exp(-x**2)", -2, 2, 16)Use --debug to print per-ke timing and progress to stderr. It does not
change the search or pollute the paste-ready C++ declaration on stdout.
Expressions use Python/NumPy syntax and may reference x, for example
sin(x), exp(-x**2), and sqrt(abs(x)). The search stops after eight
consecutive Hermite orders fail to improve the measured precision.