[JAVA程式語言] 範例1-3通過下面4點的Lagrange內插法求P(1.5)之值?
(1 , 0.0) (2 , 0.693) (3 , 1.099) (4 , 1.386)
x f(x)
==================
1.0 0.0
2.0 0.693
3.0 1.099
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])
*/
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);
}
}
STDIN資料
3 1.51.0 0.0
2.0 0.693
3.0 1.099
4.0 1.386
輸出畫面
$javac Main.java $java -Xmx128M -Xms16M Main n= 3 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 x[k]=4.00, f[k]=1.39 l=1.000000 n= 3 i= 1 l=0.500000 n= 3 i= 2 l=0.375000 n= 3 i= 3 l=0.312500 n= 3 i= 4 l=0.312500 k= 0 The value of p(1.500000)=0.000000 l=0.500000 n= 3 i= 1 l=0.500000 n= 3 i= 2 l=0.750000 n= 3 i= 3 l=0.937500 n= 3 i= 4 l=0.937500 k= 1 The value of p(1.500000)=0.649688 l=0.250000 n= 3 i= 1 l=-0.125000 n= 3 i= 2 l=-0.125000 n= 3 i= 3 l=-0.312500 n= 3 i= 4 l=-0.312500 k= 2 The value of p(1.500000)=0.306250 l=0.166667 n= 3 i= 1 l=-0.041667 n= 3 i= 2 l=0.062500 n= 3 i= 3 l=0.062500 n= 3 i= 4 l=0.062500 k= 3 The value of p(1.500000)=0.392875 The value of p(1.500000)=0.392875
沒有留言:
張貼留言