Advertisement
Guest User

Polynomial interpolation - Newton divided difference one dimensional array

a guest
Jul 5th, 2022
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. double horner(int,double*,double,double* );
  5. void invhorner(int,double*,double,double*);
  6. void newton(int,double*,double*,double*);
  7.  
  8. int main()
  9. {
  10. FILE* in;
  11. FILE* out;
  12. double *x, *y, *a;
  13. int i,n;
  14. if((in=fopen("in.txt","r"))==NULL)
  15. {
  16. printf("Nie mozna otworzyc pliku do czytania \n");
  17. exit(1);
  18. }
  19. if((out=fopen("out.txt","w"))==NULL)
  20. {
  21. printf("Nie mozna otworzyc pliku do pisania \n");
  22. exit(1);
  23. }
  24. while(!feof(in))
  25. {
  26. fscanf(in,"%d",&n);
  27. x=(double*)malloc((n+1)*sizeof(double));
  28. y=(double*)malloc((n+1)*sizeof(double));
  29. a=(double*)malloc((n+1)*sizeof(double));
  30. for(i=0; i<n; i++)
  31. fscanf(in,"%lf",&x[i]);
  32. for(i=0; i<n; i++)
  33. fscanf(in,"%lf",&y[i]);
  34. newton(n,x,y,a);
  35. for(i=0; i<n; i++)
  36. fprintf(out,"a[%d]=%.15lf\n",i,a[i]);
  37. fprintf(out,"\n");
  38. free(x);
  39. free(y);
  40. free(a);
  41. }
  42. fclose(in);
  43. fclose(out);
  44. return 0;
  45. }
  46.  
  47. double horner(int n,double* a,double c,double* b)
  48. {
  49. int i;
  50. double r;
  51. r=a[n];
  52. for(i=n-1; i>=0; i--)
  53. {
  54. b[i]=r;
  55. r=r*c+a[i];
  56. }
  57. return r;
  58. }
  59.  
  60. void invhorner(int n,double* b,double c,double* a)
  61. {
  62. int k;
  63. double* u;
  64. u=(double*)malloc((n+1)*sizeof(double));
  65. for(k=0; k<=n; k++)
  66. u[k]=b[k];
  67. a[n+1]=b[n];
  68. for(k=0; k<=n; k++)
  69. if((k-1)<0)
  70. a[k]=-c*u[k];
  71. else
  72. a[k]=u[k-1]-c*u[k];
  73. free(u);
  74. }
  75.  
  76. void newton(int n,double* x,double* y,double* a)
  77. {
  78. int i,j;
  79. double* b;
  80. double* dd;
  81. b=(double*)malloc((n+1)*sizeof(double));
  82. dd=(double*)malloc((n+1)*sizeof(double));
  83. for(i=0; i<=n; i++)
  84. {
  85. b[i]=0.0;
  86. a[i]=0.0;
  87. }
  88. for(j=0; j<=n; j++)
  89. dd[j]=y[j];
  90. for(j=1; j<=n; j++)
  91. for(i=n; i>=j; i--)
  92. dd[i]=(double)(dd[i]-dd[i-1])/(x[i]-x[i-j]);
  93. b[0]=1.0;
  94. for(i=0; i<=n; i++)
  95. {
  96. for(j=0; j<=i; j++)
  97. a[j]+=dd[i]*b[j];
  98. invhorner(i,b,x[i],b);
  99. }
  100. free(b);
  101. free(dd);
  102. }
  103.  
  104.  
  105.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement