我四处搜索了一下,但java中没有任何可用的代码,因此我自己编写了代码,遇到了一些问题。实际上,我是从一个c++源代码中获得这段代码的,并努力将其转换为一个可行的java程序。
http://ganeshtiwaridotcomdotnp.blogspot.sg/2009/12/c-c-code-lagranges-interpolation.html
public static void main(String[] args) {
int n;
int i, j;
int a;
int x[] = null;
int f[] = null;
int sum = 0;
int mult;
Scanner input = new Scanner(System.in);
System.out.println("Enter number of point: ");
n = input.nextInt();
System.out.println("Enter value x for calculation: ");
a = input.nextInt();
for (i = 0; i < n; i++) {
System.out.println("Enter all values of x and corresponding functional vale: ");
x = input.nextInt();
f = input.nextInt();
}
for (i = 0; i <= n - 1; i++) {
mult = 1;
for (j = 0; j <= n - 1; j++) {
if (j != i) {
mult *= (a - x[j]) / (x[i] - x[j]);
}
sum += mult * f[i];
}
}
System.out.println("The estimated value of f(x)= " + sum);
}
对于拉格朗日插值公式-
- 您应该使用双数据类型Array
- 您应该制作具有特定项目数的数组
看看下面的程序,你就会明白了。
double product, sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Number of Terms: ");
int n = sc.nextInt();
double[] x = new double[n];
double[] y = new double[n];
System.out.println("Enter all the x, y terms: ");
for (int i = 0; i < n; i++) {
x[i] = sc.nextDouble();
y[i] = sc.nextDouble();
}
System.out.println("x = {" + Arrays.toString(x) + "}");
System.out.println("x = {" + Arrays.toString(y) + "}");
System.out.print("Enter a point to Find it's value: ");
int xPoint = sc.nextInt();
// End of inputs
product = 1;
// Peforming Arithmatic Operation
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j != i) {
product *= (xPoint - x[j]) / (x[i] - x[j]);
}
}
sum += product * y[i];
product = 1; // Must set to 1
}
System.out.println("The value at point " + xPoint + " is : " + sum);
// End of the Program
}
}
public static void main(String[] args) {
System.out.println("Langrages");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no of terms: ");
int n = sc.nextInt();
float[] ax = new float[n];
System.out.println("Enter values of x");
for(int i=0 ;i<n;i++) {
ax[i] = sc.nextFloat();
}
float[] ay = new float[n];
System.out.println("Enter values of y");
for(int i=0 ;i<n;i++) {
ay[i] = sc.nextFloat();
}
System.out.println("Enter the value of xn at which you find y");
int x = sc.nextInt();
float num,den;
float term =0;
for(int i=0;i<n;i++) {
num=1;
den=1;
for(int j=0;j<n;j++) {
if(j!=i) {
num=num*(x-ax[j]);
den = den*(ax[i]-ax[j]);
}
}
term += (num/den)*ay[i];
}
System.out.println(term);
sc.close();
}
int x[] = null;
int f[] = null;
...
for (i = 0; i < n; i++) {
....
x = input.nextInt();
f = input.nextInt();
}
看起来很清楚。只需为x和f:创建数组实例
x = new int[n];
f = new int[n];
之后的某个地方:
n = input.nextInt();
在上述for
循环之前,修改for
主体:
...
x[i] = input.nextInt();
f[i] = input.nextInt();