Skip to content

Commit fd54a19

Browse files
authored
Handled Div by Zero Case
1 parent f11b714 commit fd54a19

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/main/java/com/thealgorithms/maths/Neville.java

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1+
// Neville.java
12
package com.thealgorithms.maths;
23

4+
import java.util.HashSet;
5+
import java.util.Set;
6+
37
/**
48
* In numerical analysis, Neville's algorithm is an algorithm used for
59
* polynomial interpolation. Given n+1 points, there is a unique polynomial
@@ -23,7 +27,7 @@ private Neville() {
2327
* @param target The x-coordinate at which to evaluate the polynomial.
2428
* @return The interpolated y-value at the target x-coordinate.
2529
* @throws IllegalArgumentException if the lengths of x and y arrays are different,
26-
* or if the arrays are empty.
30+
* if the arrays are empty, or if x-coordinates are not unique.
2731
*/
2832
public static double interpolate(double[] x, double[] y, double target) {
2933
if (x.length != y.length) {
@@ -33,6 +37,13 @@ public static double interpolate(double[] x, double[] y, double target) {
3337
throw new IllegalArgumentException("Input arrays cannot be empty.");
3438
}
3539

40+
Set<Double> seenX = new HashSet<>();
41+
for (double val : x) {
42+
if (!seenX.add(val)) {
43+
throw new IllegalArgumentException("Input x-coordinates must be unique.");
44+
}
45+
}
46+
3647
int n = x.length;
3748
double[] p = new double[n];
3849
System.arraycopy(y, 0, p, 0, n); // Initialize p with y values

0 commit comments

Comments
 (0)