Skip to content

Instantly share code, notes, and snippets.

@b3z
Last active November 26, 2021 06:55
Show Gist options
  • Save b3z/1cbf83e81fe1488a67ed04c03b3247ea to your computer and use it in GitHub Desktop.
Save b3z/1cbf83e81fe1488a67ed04c03b3247ea to your computer and use it in GitHub Desktop.
On the fly version polynomapproximation singular value decomposition
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.linear.SingularValueDecomposition;
public class Test3 {
public static void main(String[] args) {
double [][] data = {{12, 25425.6}, {15, 49816.5}, {23, 180506.9}, {27, 292460.1}};
int numCoefficients = 4; // 4 means a polynomial of rank 3 --> x3 + x2 + x1 + d
double [][] Xt_A = new double [data.length][numCoefficients];
double [] Xt_y = new double [data.length];
for (int pointIdx = 0; pointIdx < data.length; ++pointIdx) {
double x = data[pointIdx][0];
double y = data[pointIdx][1];
for(int v = 0; v < numCoefficients; ++v) {
double xv = Math.pow(x, v);
for(int w = 0; w < numCoefficients; ++w) {
double xw = Math.pow(x, w);
Xt_A[v][w] += xv * xw;
}
Xt_y[v] += xv * y;
}
}
Array2DRowRealMatrix Am = new Array2DRowRealMatrix(Xt_A);
RealMatrix ym = new Array2DRowRealMatrix(Xt_y);
SingularValueDecomposition svd = new SingularValueDecomposition(Am);
RealMatrix solution = svd.getSolver().solve(ym);
System.out.println("Solution" + solution);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment