Advertisement
Narzew

Newton polynomial

Jan 11th, 2018
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. // n nodes, n values, n. Find Newton polynomial value at a given x
  2.  
  3.  
  4. package divided.difference;
  5.  
  6. import java.util.Scanner;
  7.  
  8. /**
  9.  *
  10.  * @author Nikodem
  11.  */
  12. public class DividedDifference {
  13.  
  14.     //======================================
  15.     // ** Main
  16.     //======================================
  17.    
  18.     public static void main(String[] args) {
  19.        
  20.         double t;
  21.         double result;
  22.        
  23.         //======================================
  24.         // ** Get data from user
  25.         //======================================
  26.        
  27.         System.out.println("Enter number of values: ");
  28.         Scanner sc = new Scanner(System.in);
  29.         int n = sc.nextInt();
  30.         // Initialize vars
  31.         double[] x = new double[n];
  32.         double[] y = new double[n];
  33.        
  34.         System.out.println("Enter numbers: ");
  35.         for(int i=0; i<n; i++){
  36.             x[i] = sc.nextDouble();
  37.         }
  38.         System.out.println("Enter values: ");
  39.         for(int i=0; i<n; i++){
  40.             y[i] = sc.nextDouble();
  41.         }
  42.         System.out.println("Enter value to calculate: ");
  43.         t = sc.nextDouble();
  44.  
  45.         double[][] s = new double[n][n];
  46.        
  47.         for(int i=0;i<n;i++){
  48.             s[i][0] = y[i];
  49.         }
  50.         for(int j=1;j<n;j++){
  51.             for(int i=j;i<n;i++){
  52.                 s[i][j] = ((t-x[i-j])*s[i][j-1]+(x[i]-t)*s[i-1][j-1])/(x[i]-x[i-j]);
  53.             }
  54.         }
  55.         result = s[0][n-1];
  56.        
  57.         System.out.println("Result: "+s[0][n-1]);
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement