

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
C code implementation of newton's forward difference
Typology: Study notes
1 / 2
This page cannot be seen from the preview
Don't miss anything!


Name- Sayantan Mukherjee Roll No- 71
Newton’s Forward Difference Interpolation Program in C
Code: #include <stdio.h> #include<stdlib.h> int fact(int n) { if(n==0 || n==1) return 1; else return nfact(n-1); } float r_prod(float r, int times) { if (times==0) return 1; else { times--; return rr_prod(r-1,times); } }
int main(int argc, char const argv[]) { int n; float h,x,r,y; printf("Enter n (the number of values provided): \n"); scanf("%d",&n); float arr_x=(float) malloc(nsizeof(float)); float arr_y=(float)malloc(n*sizeof(float));
printf("Enter %d values for x:\n",n); for(int i=0;i<n;i++) scanf("%f",&arr_x[i]); printf("Enter %d values for y:\n",n); for(int i=0;i<n;i++) scanf("%f",&arr_y[i]); printf("Enter the value of x to find:\n"); scanf("%f",&x); if(x<arr_x[0] || x>arr_x[n-1]) { printf("Value of x outside range.\n"); exit(0);}
else{
int diff=(int)malloc((n-1)sizeof(int)); for(int i=0;i<n-1;i++) diff[i]=(int) malloc ((n-1)sizeof(int)); h=arr_x[1]-arr_x[0]; r= (x - arr_x[0])/h; printf("Difference Table:\n"); //first difference for(int i=0;i<n-1;i++) {diff[i][0]=arr_y[i+1] - arr_y[i]; printf("%d ",diff[i][0] );}
printf("\n"); //second and subsequent differences int k=2; for(int col=1;col<n-1;col++) { for(int row=0;row<n-k;row++) {diff[row][col]= diff[row+1][col-1] - diff[row][col-1]; printf("%d ",diff[row][col] );} printf("\n"); k++; } printf("\n\n"); y=arr_y[0]; int row=0; for(int i=1;i<n-1;i++) { y+=r_prod(r,i)* diff[0][row++]*arr_y[0]/fact(i); //printf("%f %d %d %f\n",r_prod(r,i), diff[0][row],row,y );
printf("Value of y:%f\n",y );
return 0; }
Output: Enter n (the number of values provided): 5 Enter 5 values for x: 0 1 2 3 4 Enter 5 values for y: 1 7 23 55 109 Enter the value of x to find:
Difference Table: 6 16 32 54 10 16 22 6 6 0
Value of y:3.