n=9 xa=1.5
x f(x)
=============
1.0 0.000
1.2 0.182
1.7 0.531
2.0 0.693
2.2 0.788
2.7 0.993
3.0 1.099
3.2 1.163
3.7 1.308
4.0 1.386
=============
/* 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-4 通過下面10點的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.3f",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.3f, f[k]=%2.3f",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(%2.5f)=%2.5f",l, k,xa ,ff);
System.out.println();
}
System.out.printf("The value of p(%f)=%2.5f",xa ,ff);
}
}
STDIN
9 1.5
1.0 0.000
1.2 0.182
1.7 0.531
2.0 0.693
2.2 0.788
2.7 0.993
3.0 1.099
3.2 1.163
3.7 1.308
4.0 1.386
輸出畫面
$javac Main.java $java -Xmx128M -Xms16M Main n= 9 xa=1.500 l=-0.034722 k= 0 The value of p(1.50000)=0.00000 l=0.194792 k= 1 The value of p(1.50000)=0.03545 l=1.876255 k= 2 The value of p(1.50000)=1.03174 l=-2.578125 k= 3 The value of p(1.50000)=-0.75490 l=1.947917 k= 4 The value of p(1.50000)=0.78006 l=-0.846154 k= 5 The value of p(1.50000)=-0.06017 l=0.749199 k= 6 The value of p(1.50000)=0.76320 l=-0.328125 k= 7 The value of p(1.50000)=0.38159 l=0.022222 k= 8 The value of p(1.50000)=0.41066 l=-0.003257 k= 9 The value of p(1.50000)=0.40614 The value of p(1.500000)=0.40614
沒有留言:
張貼留言