MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / interpolate

Method interpolate

src/main/java/com/thealgorithms/maths/Neville.java:33–60  ·  view source on GitHub ↗

Evaluates the polynomial that passes through the given points at a specific x-coordinate. @param x The x-coordinates of the points. Must be the same length as y. @param y The y-coordinates of the points. Must be the same length as x. @param target The x-coordinate at which to evaluate the polynomia

(double[] x, double[] y, double target)

Source from the content-addressed store, hash-verified

31 * different, if the arrays are empty, or if x-coordinates are not unique.
32 */
33 public static double interpolate(double[] x, double[] y, double target) {
34 if (x.length != y.length) {
35 throw new IllegalArgumentException("x and y arrays must have the same length.");
36 }
37 if (x.length == 0) {
38 throw new IllegalArgumentException("Input arrays cannot be empty.");
39 }
40
41 // Check for duplicate x-coordinates to prevent division by zero
42 Set<Double> seenX = new HashSet<>();
43 for (double val : x) {
44 if (!seenX.add(val)) {
45 throw new IllegalArgumentException("Input x-coordinates must be unique.");
46 }
47 }
48
49 int n = x.length;
50 double[] p = new double[n];
51 System.arraycopy(y, 0, p, 0, n); // Initialize p with y values
52
53 for (int k = 1; k < n; k++) {
54 for (int i = 0; i < n - k; i++) {
55 p[i] = ((target - x[i + k]) * p[i] + (x[i] - target) * p[i + 1]) / (x[i] - x[i + k]);
56 }
57 }
58
59 return p[0];
60 }
61}

Calls 1

addMethod · 0.45