Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
StaticBeagle committed Dec 27, 2024
1 parent 6568427 commit 7bbb4be
Showing 1 changed file with 56 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.wildbitsfoundry.etk4j.math.polynomials;

import com.wildbitsfoundry.etk4j.math.functions.UnivariateFunction;
import com.wildbitsfoundry.etk4j.util.DoubleArrays;

import java.util.Arrays;
// TODO test and javadocs
import static com.wildbitsfoundry.etk4j.util.validation.DimensionCheckers.checkXYDimensions;

public class LagrangePolynomial implements UnivariateFunction {

private final double[] x;
private final double[] y;
private final double[] weights;

public LagrangePolynomial(double[] x, double[] y) {
checkXYDimensions(x, y);
this.x = Arrays.copyOf(x, x.length);
this.y = Arrays.copyOf(y, y.length);
this.weights = computeWeights(x);
}

private double[] computeWeights(double[] x) {
int n = x.length;
double[] w = DoubleArrays.ones(n);

for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(i != j) {
w[i] /= (x[i] - x[j]);
}
}
}
return w;
}

@Override
public double evaluateAt(double x) {
double numerator = 0.0;
double denominator = 0.0;

for(int i = 0; i < this.x.length; i++) {
if(x == this.x[i]) {
return y[i];
}
double tmp = weights[i] / (x - this.x[i]);
numerator += tmp * y[i];
denominator += tmp;
}
return numerator / denominator;
}

public static LagrangePolynomial lagrangeFit(double[] x, double[] y, int n) {
return new LagrangePolynomial(x, y);
}
}

0 comments on commit 7bbb4be

Please sign in to comment.