// E06 (optional): truncation of a tiny singular value in a controlled 2x2 toy matrix.
#include <lapacke.h>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
int main() {
    constexpr lapack_int m=2,n=2;
    const std::vector<double> y{1.,1.e-8+1.e-6}; // small noise in the second component
    std::vector<double> a{1.,0.,0.,1.e-8},s(n),u(m*n),vt(n*n);
    std::vector<double> superb(std::max(1,int(n)-1));
    const lapack_int info=LAPACKE_dgesvd(LAPACK_ROW_MAJOR,'S','S',
        m,n,a.data(),n,s.data(),u.data(),n,vt.data(),n,superb.data());
    if(info!=0){std::cerr<<"LAPACKE failed: "<<info<<'\n';return 2;}
    auto solve=[&](double threshold){
        std::vector<double> x(n,0.);
        for(int k=0;k<n;++k){
            if(s[k]<=threshold)continue;
            double projection=0.;for(int i=0;i<m;++i)projection+=u[i*n+k]*y[i];
            for(int j=0;j<n;++j)x[j]+=vt[k*n+j]*projection/s[k];
        }
        return x;
    };
    const auto full=solve(0.),truncated=solve(1.e-6);
    std::cout<<std::scientific<<std::setprecision(10);
    std::cout<<"E06 OPTIONAL | sigma="<<s[0]<<", "<<s[1]<<"\n";
    std::cout<<"without truncation: x=("<<full[0]<<", "<<full[1]<<")\n";
    std::cout<<"with cutoff 1e-6: x=("<<truncated[0]<<", "<<truncated[1]<<")\n";
    std::cout<<"The noisy second datum is amplified by division by 1e-8.\n";
    return (std::abs(full[1]-101.)<1.e-8 && std::abs(truncated[1])<1.e-12)?0:1;
}
