forked from Zura1101/NUMERICAL-METHODS
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLagrange Interpolation.java
50 lines (39 loc) · 987 Bytes
/
Lagrange Interpolation.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.*;
class GFG
{
// corresponding to x and y = f(x)
static class Data
{
int x, y;
public Data(int x, int y)
{
super();
this.x = x;
this.y = y;
}
};
static double interpolate(Data f[], int xi, int n)
{
double result = 0; // Initialize result
for (int i = 0; i < n; i++)
{
// Compute individual terms of above formula
double term = f[i].y;
for (int j = 0; j < n; j++)
{
if (j != i)
term = term*(xi - f[j].x) / (f[i].x - f[j].x);
}
// Add current term to result
result += term;
}
return result;
}
public static void main(String[] args)
{
// creating an array of 4 known data points
Data f[] = {new Data(0, 2), new Data(1, 3), new Data(2, 12), new Data(5, 147)}; // manual input
// a data point corresponding to x=3
System.out.print("Value of f(3) is : " + (int)interpolate(f, 3, 4)); // manual input
}
}