/* ex1-9.java is for developing the divided-defference
* table for Newton Interpolation polynomial.
[JAVA程式語言]例題1-10牛頓的多項式內插法 已知4點座標
請建立牛頓向前與向後差除表
例題1-10 已知4點座標如下
i xi f(xi)
=============
0 1.0 0.0
1 2.0 0.693
2 3.0 1.099
3 4.0 1.386
=============
請建立牛頓向前與向後差除表
*/
import java.util.Scanner;
public class Main {
public static void main(String []args) {
Scanner scanner = new Scanner(System.in);
float[] x ;
float[][] y ;
float l ,ff;
int i, j , n ;
x = new float[10]; // 利用new指令產生物件
y = new float[10][10]; // 利用new指令產生物件
n=scanner.nextInt();
//no. of items printf("Enter n : ");
for(i=0;i<=n;i++){
x[i]=scanner.nextFloat();
y[i][0]=scanner.nextFloat();
}
//forward difference table
for(j=1;j<=n;j++){
for(i=0;i<=(n-j);i++){
y[i][j]= (y[i+1][j-1]-y[i][j-1])/(x[i+j]-x[i]);
}
}
System.out.printf("\n***********Forward Difference Table ***********\n");
System.out.printf(" ================================================\n");
System.out.printf(" i\tx(i)\tf(i)\tf(i,i+1) f(i,i+1.i+2), ......\n");
//display Forward Difference Table
for(i=0;i<=n;i++){
System.out.printf("%2d\t%.2f",i,x[i]);
for(j=0;j<=(n-i);j++){
System.out.printf("\t%.3f",y[i][j]);
}
System.out.printf("\n");
}
System.out.printf("\n***********Backward Difference Table ***********\n");
System.out.printf(" ================================================\n");
System.out.printf(" i\tx(i)\tf(i)\tf(i,i+1) f(i,i+1.i+2), ......\n");
//display Backward Difference Table
for(i=0;i<=n;i++) {
System.out.printf("%2d\t%.2f",i,x[i]);
for(j=0;j<=i;j++){
System.out.printf("\t%.3f",y[i-j][j]);
}
System.out.printf("\n");
}
}
}
STDIN:
3
1.0 0.0
2.0 0.693
3.0 1.099
4.0 1.386
輸出畫面
$javac Main.java $java -Xmx128M -Xms16M Main ***********Forward Difference Table *********** ================================================ i x(i) f(i) f(i,i+1) f(i,i+1.i+2), ...... 0 1.00 0.000 0.693 -0.144 0.028 1 2.00 0.693 0.406 -0.059 2 3.00 1.099 0.287 3 4.00 1.386 ***********Backward Difference Table *********** ================================================ i x(i) f(i) f(i,i+1) f(i,i+1.i+2), ...... 0 1.00 0.000 1 2.00 0.693 0.693 2 3.00 1.099 0.406 -0.144 3 4.00 1.386 0.287 -0.059 0.028
沒有留言:
張貼留言