Friday, 19 April 2013

C program for Cubic Spline Interpolation


#include<stdio.h>
#include<conio.h>
#include<math.h>

void main(){
clrscr();
char choice='y';
int n,i,j,k;
float h[10],a,b,c,d,sum,s[10]={0},x[10],F[10],f[10],p,m[10][10]={0},temp;

printf("No of samples? ");
scanf("%d",&n);
printf("\nEnter all sample points: ");
for(i=0;i<n;i++)
scanf("%f%f",&x[i],&f[i]);
for(i=n-1;i>0;i--){
F[i]=(f[i]-f[i-1])/(x[i]-x[i-1]);
h[i-1]=x[i]-x[i-1];
}
//*********** formation of h, s , f matrix **************//
for(i=1;i<n-1;i++){
m[i][i]=2*(h[i-1]+h[i]);
if(i!=1){
m[i][i-1]=h[i-1];
m[i-1][i]=h[i-1];
}
m[i][n-1]=6*(F[i+1]-F[i]);
}
//*********** forward elimination **************//
for(i=1;i<n-2;i++){
temp=(m[i+1][i]/m[i][i]);
for(j=1;j<=n-1;j++)
m[i+1][j]-=temp*m[i][j];
}
//*********** backward substitution *********//
for(i=n-2;i>0;i--){
sum=0;
for(j=i;j<=n-2;j++)
sum+=m[i][j]*s[j];
s[i]=(m[i][n-1]-sum)/m[i][i];
}
while(choice=='y'){
printf("\nEnter x : ");
scanf("%f",&p);
for(i=0;i<n-1;i++)
if(x[i]<=p&&p<=x[i+1]){
a=(s[i+1]-s[i])/(6*h[i]);
b=s[i]/2;
c=(f[i+1]-f[i])/h[i]-(2*h[i]*s[i]+s[i+1]*h[i])/6;
d=f[i];
sum=a*pow((p-x[i]),3)+b*pow((p-x[i]),2)+c*(p-x[i])+d;
}
printf("\nCoefficients of sub intervals are : %f\n%f\n%f\n%f",a,b,c,d);
printf("\nFunctional value is: %f",sum);
printf("\nContinue (y/n) ? ");
scanf("%c",&choice);
}
getch();
}

Sample Output:

No of samples? 5
Enter all sample points: 1     2
2     3
3     4
4     5
5     6
Enter x : 3.5
Coefficients of sub intervals are : 0.000000
0.000000
1.000000
4.000000
Functional value is: 4.500000
Continue (y/n) ?

©Dixit Bhatta 2013


7 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Replies
    1. Yes, when writing complex programs you can often end up with unused variables. You can remove 'k' from declaration to see how it behaves. I wrote this program long ago, so can't really remember, but if the program still works fine, there is no harm in removing 'k'.

      Delete
  3. Hi, I am trying to figure out what all your variables meaning, can you help me to understand about your code, I need to know the meaning of matrix, thanks!!!

    ReplyDelete
    Replies
    1. The arrays are used to hold values of f and f(x), and intermediate values. The matrix 'm' in particular is used for holding values during elimination and substitution steps, which I think is clearly labelled in the code. You will need to revisit the theory behind Cubic-Spline interpolation to fully understand.

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete

Was this post helpful? Ask any questions you have, I will try to answer them for you.

Follow by Email