|
| 1 | +package com.thealgorithms.maths; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertThrows; |
| 5 | + |
| 6 | +import org.junit.jupiter.api.Test; |
| 7 | + |
| 8 | +public class NevilleTest { |
| 9 | + |
| 10 | + @Test |
| 11 | + public void testInterpolateLinear() { |
| 12 | + // Test with a simple linear function y = 2x + 1 |
| 13 | + // Points (0, 1) and (2, 5) |
| 14 | + double[] x = {0, 2}; |
| 15 | + double[] y = {1, 5}; |
| 16 | + // We want to find y when x = 1, which should be 3 |
| 17 | + double target = 1; |
| 18 | + double expected = 3.0; |
| 19 | + assertEquals(expected, Neville.interpolate(x, y, target), 1e-9); |
| 20 | + } |
| 21 | + |
| 22 | + @Test |
| 23 | + public void testInterpolateQuadratic() { |
| 24 | + // Test with a quadratic function y = x^2 |
| 25 | + // Points (0, 0), (1, 1), (3, 9) |
| 26 | + double[] x = {0, 1, 3}; |
| 27 | + double[] y = {0, 1, 9}; |
| 28 | + // We want to find y when x = 2, which should be 4 |
| 29 | + double target = 2; |
| 30 | + double expected = 4.0; |
| 31 | + assertEquals(expected, Neville.interpolate(x, y, target), 1e-9); |
| 32 | + } |
| 33 | + |
| 34 | + @Test |
| 35 | + public void testInterpolateWithNegativeNumbers() { |
| 36 | + // Test with y = x^2 - 2x + 1 |
| 37 | + // Points (-1, 4), (0, 1), (2, 1) |
| 38 | + double[] x = {-1, 0, 2}; |
| 39 | + double[] y = {4, 1, 1}; |
| 40 | + // We want to find y when x = 1, which should be 0 |
| 41 | + double target = 1; |
| 42 | + double expected = 0.0; |
| 43 | + assertEquals(expected, Neville.interpolate(x, y, target), 1e-9); |
| 44 | + } |
| 45 | + |
| 46 | + @Test |
| 47 | + public void testMismatchedArrayLengths() { |
| 48 | + double[] x = {1, 2}; |
| 49 | + double[] y = {1}; |
| 50 | + double target = 1.5; |
| 51 | + assertThrows(IllegalArgumentException.class, () -> Neville.interpolate(x, y, target)); |
| 52 | + } |
| 53 | + |
| 54 | + @Test |
| 55 | + public void testEmptyArrays() { |
| 56 | + double[] x = {}; |
| 57 | + double[] y = {}; |
| 58 | + double target = 1; |
| 59 | + assertThrows(IllegalArgumentException.class, () -> Neville.interpolate(x, y, target)); |
| 60 | + } |
| 61 | + |
| 62 | + @Test |
| 63 | + public void testDuplicateXCoordinates() { |
| 64 | + double[] x = {1, 2, 1}; |
| 65 | + double[] y = {5, 8, 3}; |
| 66 | + double target = 1.5; |
| 67 | + assertThrows(IllegalArgumentException.class, () -> Neville.interpolate(x, y, target)); |
| 68 | + } |
| 69 | +} |
0 commit comments