2019年4月3日 星期三

[JAVA程式語言] 範例1-5 通過下面4點的Lagrange內插法求P(1.5) P(2.5) P(3.5) 之值?

[JAVA程式語言] 範例1-5 通過下面4點的Lagrange內插法求P(1.5) P(2.5) P(3.5) 之值?

/* ex1-5.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-5 通過下面4點的Lagrange內插法求P(1.5) P(2.5) P(3.5) 之值?
import java.util.Scanner;

public class Main {
    public static void main(String []args) {
        Scanner scanner = new Scanner(System.in);
        float[]  x, f, xa ;
        float  l ,ff;
        int i,k , m , n1 , n  ;
        x = new float[10]; // 利用new指令產生物件
        f = new float[10]; // 利用new指令產生物件
        xa = new float[10]; // 利用new指令產生物件
       
        n1=scanner.nextInt();
        //System.out.printf("n1=%2d",n1);
        //System.out.println();
       
        for(k=0;k<=n1;k++) {
            //Scanner scanner = new Scanner(System.in);
            xa[k]=scanner.nextFloat();
            //System.out.printf("xa[k]=%2.3f",xa[k]);
            //System.out.println();
        }
       
        n=scanner.nextInt();
        //System.out.printf("n1=%2d",n);
        //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();
        }
       
       
        for(m=0;m<=n1;m++){
       
            ff=0;
            for(k=0;k<=n;k++){
                l=1;
                i=0;
                do{
            if(i !=k) {
                    l=l*(xa[m]-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[m] ,ff);
            //System.out.println();
            }
            System.out.printf("The value of p(%f)=%2.5f",xa[m] ,ff);
            System.out.println();
        }   
    }
}

STDIN
2
1.5
2.5
3.5
3
1.0  0.000
2.0  0.693
3.0  1.099
4.0  1.386

 輸出畫面
$javac Main.java
$java -Xmx128M -Xms16M Main
The value of p(1.500000)=0.39288
The value of p(2.500000)=0.92138
The value of p(3.500000)=1.24688

沒有留言:

張貼留言

2024產專班 作業2 (純模擬)

2024產專班 作業2  (純模擬) 1) LED ON,OFF,TIMER,FLASH 模擬 (switch 控制) 2)RFID卡號模擬 (buttom  模擬RFID UID(不從ESP32) Node-Red 程式 [{"id":"d8886...