#!/usr/bin/calc -f
/* day5-ex1.calc - calculate Chebyshev coefficients using orthogonality
 *
 * calc is a small arbitary precision calculator (among other things); many
 * Linux distributions will have calc (or apcalc) as installable package, but
 * you can always build it yourself from sources, see
 * http://www.isthe.com/chongo/tech/comp/calc/index.html and
 * https://github.com/lcn2/calc/releases .
 */
config("display", 64);
config("epsilon", 1e-64);

define T(n, x)
{
    return cos(n * acos(x));
    /* in this application, the recursive definition is very slow */
    if (0 == n)
        return 1;
    else if (1 == n)
        return x;
    else
        return 2 * x * T(n - 1, x) - T(n - 2, x);
}

define coeffs(N)
{
    local i;
    for (i = 0; i < N; i = i + 1) {
        local j;
	local sum = 0;
	for (j = 0; j < N; j = j + 1) {
	    local x = cos((2 * j + 1) * pi() / (2 * N));
	    local xx = 2.5 * x + 2.5;
	    sum += exp(-xx*xx) * T(i, x);
	}
	sum /= ((0 == i) ? N : (N / 2));
	printf("coeff %02d: %32.25e\n", i, sum);
    }
}

coeffs(100)
