// E02: verify a small analytical least-squares solution. Standard C++17 only.
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
int main() {
    const std::vector<double> x{0.,1.,2.}, y{1.,2.,2.};
    const double c0=7./6., c1=0.5;
    double sse=0., normal0=0., normal1=0.;
    std::cout << std::fixed << std::setprecision(10);
    std::cout << "E02 | x     observed     fitted       residual\n";
    for (size_t i=0; i<x.size(); ++i) {
        const double prediction=c0+c1*x[i];
        const double r=prediction-y[i];
        sse+=r*r; normal0+=r; normal1+=x[i]*r;
        std::cout << x[i] << "  " << y[i] << "  " << prediction << "  " << r << '\n';
    }
    std::cout << "SSE = " << sse << " (exact 1/6 = " << 1./6. << ")\n";
    std::cout << "RMS (sqrt(SSE/m)) = " << std::sqrt(sse/x.size()) << '\n';
    std::cout << "A^T r = (" << normal0 << ", " << normal1 << ")\n";
    if (std::abs(sse-1./6.)>1e-12 || std::abs(normal0)>1e-12 || std::abs(normal1)>1e-12) return 1;
}
