Task: Chebyshev coefficients


C++: #include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <utility>
#include <vector>

using namespace std;

static const double PI = acos(-1.0);

double affine_remap(const pair<double, double>& from, double x, const pair<double, double>& to)
{
	return to.first + (x - from.first) * (to.second - to.first) / (from.second - from.first);
}

vector<double> cheb_coef(const vector<double>& f_vals)
{
	const int n = f_vals.size();
	const double theta = PI / n;
	vector<double> retval(n, 0.0);
	for (int ii = 0; ii < n; ++ii)
	{
		double f = f_vals[ii] * 2.0 / n;
		const double phi = (ii + 0.5) * theta;
		double c1 = cos(phi), s1 = sin(phi);
		double c = 1.0, s = 0.0;
		for (int j = 0; j < n; j++)
		{
			retval[j] += f * c;
			
			const double cNext = c * c1 - s * s1;
			s = c * s1 + s * c1;
			c = cNext;
		}
	}
	return retval;
}

template<class F_> vector<double> cheb_coef(const F_& func, int n, const pair<double, double>& domain)
{
	auto remap = [&](double x){return affine_remap({ -1.0, 1.0 }, x, domain); };
	const double theta = PI / n;
	vector<double> fVals(n);
	for (int ii = 0; ii < n; ++ii)
		fVals[ii] = func(remap(cos((ii + 0.5) * theta)));
	return cheb_coef(fVals);
}

double cheb_eval(const vector<double>& coef, double x)
{
	double a = 1.0, b = x, c;
	double retval = 0.5 * coef[0] + b * coef[1];
	for (auto pc = coef.begin() + 2; pc != coef.end(); a = b, b = c, ++pc)
	{
		c = 2.0 * b * x - a;
		retval += (*pc) * c;
	}
	return retval;
}
double cheb_eval(const vector<double>& coef, const pair<double, double>& domain, double x)
{
	return cheb_eval(coef, affine_remap(domain, x, { -1.0, 1.0 }));
}

struct ChebyshevApprox_
{
	vector<double> coeffs_;
	pair<double, double> domain_;

	double operator()(double x) const { return cheb_eval(coeffs_, domain_, x); }

	template<class F_> ChebyshevApprox_
		(const F_& func,
		int n,
		const pair<double, double>& domain)
		:
		coeffs_(cheb_coef(func, n, domain)),
		domain_(domain)
	{ }
};


int main(void)
{
	static const int N = 10;
	ChebyshevApprox_ fApprox(cos, N, { 0.0, 1.0 });
	cout << "Coefficients: " << setprecision(14);
	for (const auto& c : fApprox.coeffs_)
		cout << "\t" << c << "\n";

	for (;;)
	{
		cout << "Enter x, or non-numeric value to quit:\n";
		double x;
		if (!(cin >> x))
			return 0;
		cout << "True value: \t" << cos(x) << "\n";
		cout << "Approximate: \t" << fApprox(x) << "\n";
	}
}



Go: package main

import (
    "fmt"
    "math"
)

type cheb struct {
    c        []float64
    min, max float64
}

func main() {
    fn := math.Cos
    c := newCheb(0, 1, 10, 10, fn)
    fmt.Println("coefficients:")
    for _, c := range c.c {
        fmt.Printf("% .15f\n", c)
    }
    fmt.Println("\nx     computed    approximated    computed-approx")
    const n = 10
    for i := 0.; i <= n; i++ {
        x := (c.min*(n-i) + c.max*i) / n
        computed := fn(x)
        approx := c.eval(x)
        fmt.Printf("%.1f %12.8f  %12.8f   % .3e\n",
            x, computed, approx, computed-approx)
    }
}

func newCheb(min, max float64, nCoeff, nNodes int, fn func(float64) float64) *cheb {
    c := &cheb{
        c:   make([]float64, nCoeff),
        min: min,
        max: max,
    }
    f := make([]float64, nNodes)
    p := make([]float64, nNodes)
    z := .5 * (max + min)
    r := .5 * (max - min)
    for k := 0; k < nNodes; k++ {
        p[k] = math.Pi * (float64(k) + .5) / float64(nNodes)
        f[k] = fn(z + math.Cos(p[k])*r)
    }
    n2 := 2 / float64(nNodes)
    for j := 0; j < nCoeff; j++ {
        sum := 0.
        for k := 0; k < nNodes; k++ {
            sum += f[k] * math.Cos(float64(j)*p[k])
        }
        c.c[j] = sum * n2
    }
    return c
}

func (c *cheb) eval(x float64) float64 {
    x1 := (2*x - c.min - c.max) / (c.max - c.min)
    x2 := 2 * x1
    var s, t float64
    for j := len(c.c) - 1; j >= 1; j-- {
        t, s = x2*t-s+c.c[j], t
    }
    return x1*t - s + .5*c.c[0]
}