-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
6568427
commit 7bbb4be
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
56 changes: 56 additions & 0 deletions
56
src/main/java/com/wildbitsfoundry/etk4j/math/polynomials/LagrangePolynomial.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |