/* ex1-4.java: Lagrange Interpolation Algorithm
* Read in data file of ex1-4.dat which has n point values
* and the value of interpolating point xa. Based on Lagrange
* Interpolation algorithm to compute p(xa) and output its value.
* (x[i],f[i]):given points and n+1 are number of points
* Ln,k(x)=l=summation of (x-x[i])/(x[k]-x[i]).
* p(x)=ff=L(x)*f(x[k])
*/
// 範例1-2 通過下面3點的Lagrange內插法求P(1.5)之值?
import java.util.Scanner;
public class Main {
public static void main(String []args) {
Scanner scanner = new Scanner(System.in);
float[] x, f ;
float xa , l ,ff;
int i,k,n;
x = new float[10]; // 利用new指令產生物件
f = new float[10]; // 利用new指令產生物件
n=scanner.nextInt();
xa=scanner.nextFloat();
System.out.printf("n=%2d\txa=%2.2f",n,xa);
System.out.println();
for(k=0;k<=n;k++)
{
//Scanner scanner = new Scanner(System.in);
x[k]=scanner.nextFloat();
f[k]=scanner.nextFloat();
System.out.printf("x[k]=%2.2f, f[k]=%2.2f",x[k],f[k]);
System.out.println();
}
ff=0;
for(k=0;k<=n;k++){
l=1;
i=0;
do{
if(i !=k) {
l=l*(xa-x[i])/(x[k]-x[i]);
}
i=i+1;
System.out.printf("l=%f n=%2d i=%2d",l, n, i);
System.out.println();
} while (i<=n);
ff=ff+l*f[k];
System.out.printf("l=%f k=%2d The value of p(%f)=%f",l, k,xa ,ff);
System.out.println();
}
System.out.printf("The value of p(%f)=%f",xa ,ff);
}
}
2 1.5
1.0 0.0
2.0 0.693
3.0 1.099
輸出畫面
$javac Main.java $java -Xmx128M -Xms16M Main n= 2 xa=1.50 x[k]=1.00, f[k]=0.00 x[k]=2.00, f[k]=0.69 x[k]=3.00, f[k]=1.10 l=1.000000 n= 2 i= 1 l=0.500000 n= 2 i= 2 l=0.375000 n= 2 i= 3 l=0.375000 k= 0 The value of p(1.500000)=0.000000 l=0.500000 n= 2 i= 1 l=0.500000 n= 2 i= 2 l=0.750000 n= 2 i= 3 l=0.750000 k= 1 The value of p(1.500000)=0.519750 l=0.250000 n= 2 i= 1 l=-0.125000 n= 2 i= 2 l=-0.125000 n= 2 i= 3 l=-0.125000 k= 2 The value of p(1.500000)=0.382375 The value of p(1.500000)=0.382375
沒有留言:
張貼留言