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

class Vandermonde2
{
//Vandermonde interpolation
public static double[] Vandermonde_coef(double x[], double y[])
{
//========
void polint(float xa[], float ya[], int n, float x, float *y, float *dy);
int k,j,i;
float xmin,dy,*x,*y;
122 Chapter 3. Interpolation and Extrapolation
x=vector(0,n);
y=vector(0,n);
for (j=0;j<=n;j++) {
x[j]=xa[j];
y[j]=ya[j];
}
for (j=0;j<=n;j++) {
polint(x-1,y-1,n+1-j,0.0,&cof[j],&dy);
Subtract 1 from the pointers to x and y because polint uses dimensions [1..n]. We
extrapolate to x = 0.
xmin=1.0e38;
k = -1;
for (i=0;i<=n-j;i++) { Find the remaining xi of smallest
if (fabs(x[i]) < xmin) { absolute value,
xmin=fabs(x[i]);
k=i;
}
if (x[i]) y[i]=(y[i]-cof[j])/x[i]; (meanwhile reducing all the terms)
}
for (i=k+1;i<=n-j;i++) { and eliminate it.
y[i-1]=y[i];
x[i-1]=x[i];
}
}
free_vector(y,0,n);
free_vector(x,0,n);
}
//========	
}

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,10);
  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();
  }
}