import java.io.*;
import java.util.*;
import javax.swing.*;

class Vandermonde1
{
//Vandermonde interpolation
public static double[] Vandermonde_coef(double x[], double y[])
{
int n=x.length-1;
double cof[]=new double[n+1];
int k,j,i;
double phi,ff,b;
double s[]=new double[n+1];
s[n] = -x[0];
for (i=1;i<=n;i++) { 
for (j=n-i;j<=(n-1);j++) 
s[j] -= x[i]*s[j+1];
s[n] -= x[i];
}
for (j=0;j<=n;j++) {
phi=n+1;
for (k=n;k>=1;k--) 
phi=k*s[k]+x[j]*phi; 
ff=y[j]/phi;
b=1.0; 
for (k=n;k>=0;k--) 
{
cof[k] += b*ff;
b=s[k]+x[j]*b;
}
}
return cof;
}

public static double func(double c[],double x)
{
// this function calculates the value of
// least square curve fitting function
int n=c.length;
double ff=0;
double xx=1.0;
if(n!=0.0)
  { xx=1.0;
  for(int i=0;i<n;i++)
   {ff+=c[i]*xx;
    xx*=x;
   }
  } 
return ff;
}

public static double[][]  Vandermonde(double xi[],double yi[],int aradegersayisi)
 {
	//aradegersayisi:  x--o--o--x--o--o--x zincirinde x deneysel noktalar ise
	// ara değer sayısı 2 dir
	int n=xi.length;
	int nn=(n-1)*(aradegersayisi+1)+1;
	double z[][]=new double[2][nn];
    double E[]=Vandermonde_coef(xi,yi);	
    System.out.println("katsayılar :\n"+Matrix.toStringT(E));
    double dx=0;
    int k=0;
    int i;
    for(i=0;i<(n-1);i++)
       {z[0][k]=xi[i];z[1][k]=func(E,z[0][k]);k++;
       for(int j=0;j<aradegersayisi;j++) 
       {dx=(xi[i+1]-xi[i])/((double)aradegersayisi+1.0);
       z[0][k]=z[0][k-1]+dx;z[1][k]=func(E,z[0][k]);k++;}
       }
       z[0][k]=xi[i];z[1][k]=func(E,z[0][k]);
    return z;
 } 

  public static void main(String args[]) throws IOException
  {
  double x[];
  double y[];
  String s1=JOptionPane.showInputDialog("Data file name (input1.txt)");
  // JFileChooser fc=new JFileChooser();
  // if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {File file = fc.getSelectedFile();s1=file.getName(); }
  double a[][]=Text.readDoubleT(s1);
  x=a[0];
  y=a[1];
  double z[][]=Vandermonde(x,y,2);
  System.out.println("Vandermonde interpolation curve fitting\n"+Matrix.toStringT(z)); 
  Plot pp=new Plot(a[0],a[1]);
  pp.setPlabel("Vandermonde interpolation curve fitting");
  pp.setXlabel("x");
  pp.setYlabel("y=f(x)");
  pp.setPlotType(0,22); 
  pp.addData(z[0],z[1]);
  pp.setPlotType(1,0); 
  pp.setGrid(1,1);
  pp.plot();
  }
}